如何使用反射调用泛型类的静态属性?

Jam*_*mes 9 .net c# generics reflection

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

public class Foo<T> {
    public static string MyProperty {
         get {return "Method: " + typeof( T ).ToString(); }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Type myType = typeof( string );
string myProp = ???;
Console.WriteLinte( myMethodResult );
Run Code Online (Sandbox Code Playgroud)

我试过的:

我知道如何用反射实例化泛型类:

Type myGenericClass = typeof(Foo<>).MakeGenericType( 
    new Type[] { typeof(string) }
);
object o = Activator.CreateInstance( myGenericClass );
Run Code Online (Sandbox Code Playgroud)

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

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

Dar*_*rov 6

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)