Create instance of generic class with dynamic generic type parameter

后端 未结 2 682
攒了一身酷
攒了一身酷 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.

    0 讨论(0)
  • 2021-01-14 02:22

    Looks like you're almost there:

    // t is a variable, so make it lowercase. This is where some of the confusion comes from
    Type t = Type.GetType(className).GetMethod(functionName).ReturnType;
    Type myGeneric = typeof(IEqualityComparer<>);
    
    // You need to provide the generic type to make it generic with
    // You want IEqualityComparer<T>, so:
    Type constructedClass = myGeneric.MakeGenericType(t); 
    
    // Now create the object
    object created = Activator.CreateInstance(constructedClass);
    
    // This is tricky without more context...
    // You could try this, but to tell you more I would need to know where you use
    // the comparer instance. Are you using it in a LINQ query, or in a Sort()?
    // If so just cast it to a IEqualityComparer<YourType>, and
    // make YourType whaterver you need it to be in the list or the query...
    var comparer = (IEqualityComparer<object>)created;
    
    0 讨论(0)
提交回复
热议问题