Create instance of generic class with dynamic generic type parameter

后端 未结 2 684
攒了一身酷
攒了一身酷 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: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, 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, and
    // make YourType whaterver you need it to be in the list or the query...
    var comparer = (IEqualityComparer)created;
    
        

    提交回复
    热议问题