Create instance of generic class with dynamic generic type parameter

后端 未结 2 697
攒了一身酷
攒了一身酷 2021-01-14 01:26

I need to create instance of a generic class like this:

 Type T = Type.GetType(className).GetMethod(functionName).ReturnType;
 var comparer = new MyComparer&         


        
2条回答
  •  温柔的废话
    2021-01-14 02:15

    I found very simple solution to problem. There is no need to cast object to specific type T, just use dynamic keyword instead of casting

       Type myGeneric = typeof(MyComparer<>);
       Type constructedClass = myGeneric.MakeGenericType(T);
       object created = Activator.CreateInstance(constructedClass);
       dynamic comparer = created; // No need to cast created object to T
    

    and then I can use comparer normally to call its methods like:

       return comparer.Equals(myResultAsT, correctResultAsT);
    

    According to LueTm comments, it is probably possible to use reflection again and call comparer methods, but this solution looks much easier.

提交回复
热议问题