是否可以实现以下代码?我知道它不起作用,但我想知道是否有解决方法?
Type k = typeof(double);
List<k> lst = new List<k>();
Run Code Online (Sandbox Code Playgroud) 我有以下示例类:
public class MyClass<T>
{
public IList<T> GetAll()
{
return null; // of course, something more meaningfull happens here...
}
}
Run Code Online (Sandbox Code Playgroud)
我想GetAll用反思来调用:
Type myClassType = typeof(MyClass<>);
Type[] typeArgs = { typeof(object) };
Type constructed = myClassType.MakeGenericType(typeArgs);
var myClassInstance = Activator.CreateInstance(constructed);
MethodInfo getAllMethod = myClassType.GetMethod("GetAll", new Type[] {});
object magicValue = getAllMethod.Invoke(myClassInstance, null);
Run Code Online (Sandbox Code Playgroud)
这导致(在上面的代码的最后一行):
无法对ContainsGenericParameters为true的类型或方法执行后期绑定操作.
好的,第二次尝试:
MethodInfo getAllMethod = myClassType.GetMethod("GetAll", new Type[] {});
getAllMethod = getAllMethod.MakeGenericMethod(typeof(object));
object magicValue = getAllMethod.Invoke(myClassInstance, null);
Run Code Online (Sandbox Code Playgroud)
这导致(在上面代码的倒数第二行):
System.Collections.Generic.IList`1 [T] GetAll()不是GenericMethodDefinition.MakeGenericMethod只能在MethodBase.IsGenericMethodDefinition为true的方法上调用.
我在这做错了什么?