如何使用reflection调用generics类的静态属性?

我有一个类(我无法修改)简化为:

public class Foo { public static string MyProperty { get {return "Method: " + typeof( T ).ToString(); } } } 

我想知道当我只有一个System.Type时如何调用这个方法

 Type myType = typeof( string ); string myProp = ???; Console.WriteLinte( myMethodResult ); 

我试过的:

我知道如何使用reflection实例化generics类:

 Type myGenericClass = typeof(Foo).MakeGenericType( new Type[] { typeof(string) } ); object o = Activator.CreateInstance( myGenericClass ); 

但是,由于我使用静态属性,这是否适合实例化一个类? 如果我无法编译时间,如何获得对该方法的访问权限? (System.Object没有static MyProperty的定义)

编辑我发布后意识到,我正在使用的类是属性,而不是方法。 我为这种困惑道歉

该方法是静态的,因此您不需要对象的实例。 你可以直接调用它:

 public class Foo { 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); } } 

好吧,你不需要一个实例来调用静态方法:

 Type myGenericClass = typeof(Foo<>).MakeGenericType( new Type[] { typeof(string) } ); 

没问题……那么,简单地说:

 var property = myGenericClass.GetProperty("MyProperty").GetGetMethod().Invoke(null, new object[0]); 

应该这样做。

 typeof(Foo<>) .MakeGenericType(typeof(string)) .GetProperty("MyProperty") .GetValue(null, null); 

你需要这样的东西:

 typeof(Foo) .GetProperty("MyProperty") .GetGetMethod() .Invoke(null, new object[0]);