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

前端 未结 4 1793
暗喜
暗喜 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:34

    You need something like this:

    typeof(Foo<string>)
        .GetProperty("MyProperty")
        .GetGetMethod()
        .Invoke(null, new object[0]);
    
    0 讨论(0)
  • 2021-01-04 20:38

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-04 20:47
    typeof(Foo<>)
        .MakeGenericType(typeof(string))
        .GetProperty("MyProperty")
        .GetValue(null, null);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题