jeudi 27 juillet 2017

Creating new instances for objects in dictionary

I made project Animal and set it as Library. Of course in Animal project I'll add more classes. In this project I have 2 classes for now: Dog and Method.

//Class Method
public class Method : Attribute{
    public string Name { get; set; }
    public Method(){
        Name = "";
    }
}

//Class Dog
[Method(Name = "dog")]
public class Dog
{
    public int NumberOfLegs { get; set; }
    public string Breed { get; set; }
    public Dog() { }
}

Then I created second project in my solution Ref and it is my main class:

//version 1
class Program{
    public static Dictionary<String, Type> animals;
    static void Main(string[] args){
        Assembly assembly = Assembly.GetEntryAssembly();
        Type[] typ = assembly.GetTypes();
        foreach (Type t in typ){
            animals.Add(t.Name, t);
        }
    }
}

I want achieve "dog, Dog", "cat, Cat", "rat, Rat". Where "dog" is name attribute and "Dog" is a type thanks to I will be able to make something like

Activator.CreateInstance(animals[nameAnimal]);

But for now I do something wrong, my way doesn't work and I cannot find working solution for my problem in .net core. I want only object from classes where is Attribute Method. How achieve it?





Aucun commentaire:

Enregistrer un commentaire