代码之家  ›  专栏  ›  技术社区  ›  Richard Neil Ilagan

使用类型对象创建泛型

  •  7
  • Richard Neil Ilagan  · 技术社区  · 16 年前

    我正在尝试使用类型对象创建泛型类的实例。

    基本上,在运行时,我将拥有一个不同类型的对象集合,由于无法确定它们到底是什么类型,我想我将不得不使用反射。

    我在做这样的工作:

    Type elType = Type.GetType(obj);
    Type genType = typeof(GenericType<>).MakeGenericType(elType);
    object obj = Activator.CreateInstance(genType);
    

    很好很好。^ ^ ^ ^

    问题是,我想访问我的generictype<>实例的方法,但我不能访问,因为它是作为对象类类型的。我找不到将它转换为特定泛型的方法,因为这首先是问题所在(即,我无法放入类似的内容:)

    ((GenericType<elType>)obj).MyMethod();
    

    我们应该如何着手解决这个问题?

    非常感谢!^ ^ ^ ^

    7 回复  |  直到 16 年前
        1
  •  5
  •   Aaronaught    16 年前

    您必须继续使用反射来调用实际方法:

    // Your code
    Type elType = Type.GetType(obj);
    Type genType = typeof(GenericType<>).MakeGenericType(elType);
    object obj = Activator.CreateInstance(genType);
    
    // To execute the method
    MethodInfo method = genType.GetMethod("MyMethod",
        BindingFlags.Instance | BindingFlags.Public);
    method.Invoke(obj, null);
    

    有关详细信息,请参见 Type.GetMethod MethodBase.Invoke .

        2
  •  4
  •   Darin Dimitrov    16 年前

    一旦你开始反思游戏,你就必须玩到最后。类型在编译时未知,因此无法强制转换它。必须通过反射调用方法:

    obj.GetType().InvokeMember(
        "MyMethod", 
        BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, 
        null, 
        obj, 
        null
    );
    
        3
  •  3
  •   Randolpho    16 年前

    在C 3.5中,您必须使用 Type.GetMethod MethodInfo.Invoke 调用方法。

    在C 4中,您可以使用 dynamic 关键字并在运行时绑定到方法。

        4
  •  2
  •   Jeffrey Hantin    16 年前

    最直接的方法是从generictype中提取非泛型超类型(基类或接口),generictype包含要为此目的公开的方法:

    class GenericType<T> : GenericBase { ... }
    class GenericBase { abstract void MyMethod(); }
    

    否则,使用反射来访问@aaronaught建议的方法本身。

        5
  •  1
  •   Reed Copsey    16 年前

    创建实例后,只需执行以下操作:

    MethodInfo method = genType.GetMethod("MyMethod");
    method.Invoke(obj, null);
    
        6
  •  0
  •   Lucero    16 年前

    如果知道要调用的方法的签名,则不能只使用 MethodInfo.Invoke() 如这里的其他示例所示,还可以创建一个委托,该委托允许使用 Delegate.CreateDelegate() .

        7
  •  0
  •   Mark Synowiec    16 年前

    我不确定类型的变化有多大,也不知道是否可以控制将要在其中调用的方法,但是创建一个接口来定义将要调用的函数集可能会很有用。因此,在创建实例之后,可以强制转换到接口并调用所需的任何函数。

    因此,创建您的标准接口(如果您可以控制它们,则需要在每种类型中实现这些接口):

    interface IMyInterface
    {
       void A();
       int  B();
    }
    
    class One : IMyInterface
    {
       ...
       implement A and B
       ...
    }
    
    Type elType = Type.GetType(obj);
    Type genType = typeof(GenericType<>).MakeGenericType(elType);
    IMyInterface obj = (IMyInterface)Activator.CreateInstance(genType);
    obj.A();