这是我的问题;
public class MyClass<T>
{
public void DoSomething(T obj)
{
....
}
}
我所做的是:
var classType = typeof(MyClass<>);
Type[] classTypeArgs = { typeof(T) };
var genericClass = classType.MakeGenericType(classTypeArgs);
var classInstance = Activator.CreateInstance(genericClass);
var method = classType.GetMethod("DoSomething", new[]{typeof(T)});
method.Invoke(classInstance, new[]{"Hello"});
在上述情况下,我得到的异常是:无法对 ContainsGenericParameters 为 true 的类型或方法执行后期绑定操作。
如果我尝试使该方法通用,它会再次失败并出现异常:
MakeGenericMethod 只能在 MethodBase.IsGenericMethodDefinition 为 true 的方法上调用。
我应该如何调用该方法?
你正在呼唤GetMethod
在错误的对象上。调用它与bound通用类型,它应该可以工作。这是一个可以正常工作的完整示例:
using System;
using System.Reflection;
internal sealed class Program
{
private static void Main(string[] args)
{
Type unboundGenericType = typeof(MyClass<>);
Type boundGenericType = unboundGenericType.MakeGenericType(typeof(string));
MethodInfo doSomethingMethod = boundGenericType.GetMethod("DoSomething");
object instance = Activator.CreateInstance(boundGenericType);
doSomethingMethod.Invoke(instance, new object[] { "Hello" });
}
private sealed class MyClass<T>
{
public void DoSomething(T obj)
{
Console.WriteLine(obj);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)