How do I call a static property of a generic class with reflection?

前端 未结 4 1823
暗喜
暗喜 2021-01-04 20:30

I have a class (that I cannot modify) that simplifies to this:

public class Foo {
    public static string MyProperty {
         get {return \"Metho         


        
4条回答
  •  佛祖请我去吃肉
    2021-01-04 20:49

    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.

提交回复
热议问题