相关疑难解决方法(0)

使用包含Type的变量创建Generic <T>类型实例

是否可以实现以下代码?我知道它不起作用,但我想知道是否有解决方法?

Type k = typeof(double);
List<k> lst = new List<k>();
Run Code Online (Sandbox Code Playgroud)

c# generics types instance

82
推荐指数
1
解决办法
4万
查看次数

反射:作为结果使用通用列表调用方法

我有以下示例类:

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的方法上调用.

我在这做错了什么?

c# generics reflection

4
推荐指数
1
解决办法
4002
查看次数

标签 统计

c# ×2

generics ×2

instance ×1

reflection ×1

types ×1