使用动态泛型类型参数创建泛型类的实例 [英] Create instance of generic class with dynamic generic type parameter

查看:99
本文介绍了使用动态泛型类型参数创建泛型类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个通用类的实例,如下所示:

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

 Type T = Type.GetType(className).GetMethod(functionName).ReturnType;
 var comparer = new MyComparer<T>(); // ERROR: "The type or namespace name 'T' could not be found"

我发现了这个答案,其中只有通过反射才能实现。但是使用反射,我得到了需要转换为通用类型的对象。我这样尝试过

I found this answer where this is possible only with reflection. But using reflection I get object which I need to cast to my generic type. I tried like this

 Type myGeneric = typeof(MyComparer<>);
 Type constructedClass = myGeneric.MakeGenericType();
 object created = Activator.CreateInstance(constructedClass);
 var comparer = (T)Convert.ChangeType(created, T);// ERROR: "The type or namespace name 'T' could not be found"

,但得到相同的错误。

but get the same error. How to solve it?

这里是一个完整的示例:

Here is a complete example:

    public static bool Test(string className, string functionName, object[] parameters, object correctResult)
    {
        var method = Type.GetType(className).GetMethod(functionName);
        Type T = method.ReturnType;
        var myResult = method.Invoke(null, parameters);
        dynamic myResultAsT = Convert.ChangeType(myResult, T);
        dynamic correctResultAsT = Convert.ChangeType(correctResult, T);
        var comparer = new MyComparer<T>();    // Problem is here!!!       
        return comparer.Equals(myResultAsT, correctResultAsT);            
    }

这个想法是进行单元测试,该测试将调用带有参数和将其结果与正确的结果进行比较。但是我需要自定义比较器,因此我实现了 MyComparer ,由于编译器错误而无法使用。

The idea is to make a unit test which will call a function with parameters and compare its result with the correct result. But I need custom comparer, so I implement MyComparer which I cannot use because of a compiler error.

public class MyComparer<T> : IEqualityComparer<T>
{
    public bool Equals(T x, T y){/* some implementation*/}
}


推荐答案

我找到了非常简单的问题解决方案。无需将对象强制转换为特定类型 T ,只需使用 dynamic 关键字而不是强制转换

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);

根据 LueTm 注释,可能可以再次使用反射并调用比较器方法,但是此解决方案看起来容易得多。

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

这篇关于使用动态泛型类型参数创建泛型类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆