【问题标题】:How do I call a static property of a generic class with reflection?如何使用反射调用泛型类的静态属性?
【发布时间】:2012-07-09 14:06:19
【问题描述】:

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

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

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

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 的定义)

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

【问题讨论】:

标签: c# .net generics reflection


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    没关系...那么,简单地说:

    var property = myGenericClass.GetProperty("MyProperty").GetGetMethod().Invoke(null, new object[0]);
    

    应该这样做。

    【讨论】:

      【解决方案3】:
      typeof(Foo<>)
          .MakeGenericType(typeof(string))
          .GetProperty("MyProperty")
          .GetValue(null, null);
      

      【讨论】:

      • 这可能适用于我知道我将使用 system.string,但我不知道编译时的类型
      【解决方案4】:

      你需要这样的东西:

      typeof(Foo<string>)
          .GetProperty("MyProperty")
          .GetGetMethod()
          .Invoke(null, new object[0]);
      

      【讨论】:

        猜你喜欢
        • 2018-10-30
        • 1970-01-01
        • 1970-01-01
        • 2016-05-10
        • 2010-10-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-23
        相关资源
        最近更新 更多