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

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

    The method is static, so you don't need an instance of an object. You could directly invoke it:

    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);
        }
    }
    

提交回复
热议问题