【问题标题】:How to get class of type [duplicate]如何获得类型的类[重复]
【发布时间】:2011-02-01 05:54:09
【问题描述】:

我需要使用如下方法:

DoSomething<(T)>();

但我不知道我有哪种类型,只有类型的对象。如果我只有:如何调用此方法:

Type typeOfGeneric;

【问题讨论】:

  • 你的问题不是很清楚。你能举一个更具体的例子吗?
  • 我们需要比这更多的细节......也许一两个代码示例会有所帮助。
  • @Jon Skeet,真的,你不能既编辑一个男人的帖子试图澄清你想象的样子,又抱怨帖子不清楚...... :-)

标签: c# generics


【解决方案1】:

您使用反射(假设DoSomething() 是静态的):

var methodInfo = typeOfGeneric.GetMethod( "DoSomething" );
methodInfo.Invoke( null, null );

编辑:当我写下答案时,您的问题发生了变化。上面的代码是针对非泛型方法的,这里是针对泛型类的:

var constructedType = someType.MakeGenericMethod( typeOfGeneric );
var methodInfo = constructedType.GetMethod( "DoSomething" );
methodInfo.Invoke( null, null );

这里是针对非泛型类的静态泛型方法:

var typeOfClass = typeof(ClassWithGenericStaticMethod);

MethodInfo methodInfo = typeOfClass.GetMethod("DoSomething",   
    System.Reflection.BindingFlags.Static | BindingFlags.Public);

MethodInfo genericMethodInfo = 
    methodInfo.MakeGenericMethod(new Type[] { typeOfGeneric });

genericMethodInfo.Invoke(null, new object[] { "hello" });

【讨论】:

  • 我想你没有得到我的问题。如何将 Type 对象作为泛型参数传递?
【解决方案2】:

如果您只有一个类型指定为类型,则必须构建泛型方法,并通过反射调用它。

Type thisType = this.GetType(); // Get your current class type
MethodInfo doSomethingInfo = thisType.GetMethod("DoSomething");

MethodInfo concreteDoSomething = doSomethingInfo.MakeGenericMethod(typeOfGeneric);
concreteDoSomething.Invoke(this, null);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-27
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    相关资源
    最近更新 更多