[英]How do I call a static property of a generic class with reflection?
I have a class (that I cannot modify) that simplifies to this:我有一个类(我无法修改)可以简化为:
public class Foo<T> {
public static string MyProperty {
get {return "Method: " + typeof( T ).ToString(); }
}
}
I would like to know how to call this method when I only have a System.Type
我想知道当我只有System.Type
时如何调用此方法
ie IE
Type myType = typeof( string );
string myProp = ???;
Console.WriteLinte( myMethodResult );
What I've Tried:我试过的:
I know how to instantiate generics classes with reflection:我知道如何使用反射实例化泛型类:
Type myGenericClass = typeof(Foo<>).MakeGenericType(
new Type[] { typeof(string) }
);
object o = Activator.CreateInstance( myGenericClass );
However, is this proper to instantiate a class since I am using the static property?但是,因为我使用的是静态属性,所以实例化一个类是否合适? How do I gain access to the method if I can't compile time cast it?如果我无法编译时投射它,我如何获得对该方法的访问权限? (System.Object does not have a definition for static MyProperty
) ( System.Object 没有static MyProperty
的定义)
Edit I realized after posting, the class I'm working with is a property, not a method.编辑发布后我意识到,我正在使用的类是一个属性,而不是一个方法。 I apologize for the confusion我为混乱道歉
The method is static, so you don't need an instance of an object.该方法是静态的,因此您不需要对象的实例。 You could directly invoke it:你可以直接调用它:
public class Foo<T>
{
public static string MyMethod()
{
return "Method: " + typeof(T).ToString();
}
}
class Program
{
static void Main()
{
Type myType = typeof(string);
var fooType = typeof(Foo<>).MakeGenericType(myType);
var myMethod = fooType.GetMethod("MyMethod", BindingFlags.Static | BindingFlags.Public);
var result = (string)myMethod.Invoke(null, null);
Console.WriteLine(result);
}
}
Well, you don't need an instance to call a static method:好吧,您不需要实例来调用静态方法:
Type myGenericClass = typeof(Foo<>).MakeGenericType(
new Type[] { typeof(string) }
);
Is OK... then, simply:可以……那么,简单地说:
var property = myGenericClass.GetProperty("MyProperty").GetGetMethod().Invoke(null, new object[0]);
should do it.应该这样做。
typeof(Foo<>)
.MakeGenericType(typeof(string))
.GetProperty("MyProperty")
.GetValue(null, null);
You need something like this:你需要这样的东西:
typeof(Foo<string>)
.GetProperty("MyProperty")
.GetGetMethod()
.Invoke(null, new object[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.