如何获得类类型
问题描述:
答
如果你只有一个指定为Type的Type,你必须建立泛型方法,并通过反射来调用它。
Type thisType = this.GetType(); // Get your current class type
MethodInfo doSomethingInfo = thisType.GetMethod("DoSomething");
MethodInfo concreteDoSomething = doSomethingInfo.MakeGenericMethod(typeOfGeneric);
concreteDoSomething.Invoke(this, null);
答
您使用反射(假设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" });
+0
我认为你没有得到我的问题。如何传递Type对象作为泛型参数? – wassertim 2010-03-26 15:52:22
你的问题不是很清楚。你能举一个更具体的例子吗? – 2010-03-26 15:49:03
我们将需要比这更多的细节...也许一个代码示例或两个会有所帮助。 – 2010-03-26 15:49:22
@Jon Skeet,真的,你不能同时编辑一个男人的帖子,试图澄清你的想法是怎么样的,并抱怨帖子不清楚...... :-) – 2010-03-26 15:51:08