我正在尝试通过反射设置通用列表的类型 T。这是我的代码:
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>))
{
Type itemType = propertyType.GetGenericArguments()[0];
var result = MyGenericMethod<itemType>(url);
}
这给了我一个语法错误。如何通过反射设置泛型类型的类型参数 T ?
谢谢
最佳答案
您可以通过利用 Invoke
和 MakeGenericMethod
来使用反射来完成此操作。
您需要知道它正在执行的类的名称,我们称之为ClassName
。绑定(bind)标志也非常重要,如果它们不正确(这里猜测是因为您没有显示方法签名),那么 MethodInfo 将为 null 并且您将得到一个异常。
if(/*noted conditions in question*/)
{
Type itemType = propertyType.GetGenericArguments()[0];
Type ThisClass = typeof(ClassName);
MethodInfo mi = ThisClass.GetMethod("MyGenericMethod", BindingFlags.Instance | BindingFlags.NonPublic);
MethodInfo miConstructed = mi.MakeGenericMethod(itemType);
object[] args = { url };
var result = miConstructed.Invoke(this, args);
}
关于C# 泛型通过反射动态指定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22941474/