【发布时间】:2010-03-18 18:28:44
【问题描述】:
我在 c# 中有一个通用方法:
public IList<T> getList<T>();
当我像下面这样称呼它时?
...
Type T1=metadata.ModelType;
getList<T1>();
...
编译时出错。
我该怎么做呢? 我真的需要将类型作为变量传递给泛型方法!
【问题讨论】:
我在 c# 中有一个通用方法:
public IList<T> getList<T>();
当我像下面这样称呼它时?
...
Type T1=metadata.ModelType;
getList<T1>();
...
编译时出错。
我该怎么做呢? 我真的需要将类型作为变量传递给泛型方法!
【问题讨论】:
泛型参数是一个类型参数:
getList<string>(); // Return a list of strings
getList<int>(); // Return a list of integers
getList<MyClass>(); // Return a list of MyClass
你不是用 type 而是用一个对象来调用它。
【讨论】:
正如 Oded 指出的那样,您不能按照您尝试的方式执行此操作,因为 <T> 不接受类型。但是,您可以使用反射实现您想要的:
Type T1=metadata.ModelType;
MethodInfo method = GetType().GetMethod("getList");
MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { T1 });
genericMethod.Invoke(this, null);
如果getList 是一个静态方法,或者在另一个类中,您需要将GetType() 替换为typeof(...),其中... 是类的名称。
【讨论】:
您不能:在您的示例中,T1 是 System.Type 类的一个实例,而不是像 IList 这样的实际类型
【讨论】: