jeudi 25 avril 2019

How to initialize a dynamic class that has a constructor

I have the following class:

public class CustomItem
{
    //....
}

and there are multiple classes which accept CustomClass in their constructor methods. e.g:

public class FirstClass
{
   public FirstClass(CustomItem customItem) { }
}

I am trying to create a generic method which accepts a dynamic class and initialize it. Something like this:

public List<T> MyTestMethod<T>(CustomItem myCustomItem) where T : class, new()
{
   List<T> list = new List<T>();
   foreach(CustomItem myCustomItem in listOfCustomItems)
   {
      T instance = new T(myCustomItem);
      list.Add(T);
   }
   return list;
}

So, that it can be used like:

List<FirstClass> List1 = MyTestMethod<FirstClass>(customItem);
List<SecondClass> List2 = MyTestMethod<SecondClass>(customItem);

The syntax to instantiate T in MyTestMethod is incorrect. Is what I'm trying to do, possible?





Aucun commentaire:

Enregistrer un commentaire