繁体   English   中英

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

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

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

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

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

IE

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

我试过的:

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

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

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

编辑发布后我意识到,我正在使用的类是一个属性,而不是一个方法。 我为混乱道歉

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

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

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

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<string>)
    .GetProperty("MyProperty")
    .GetGetMethod()
    .Invoke(null, new object[0]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM