簡體   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