简体   繁体   中英

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

I have a class (that I cannot modify) that simplifies to this:

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

I would like to know how to call this method when I only have a System.Type

ie

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

What I've Tried:

I know how to instantiate generics classes with reflection:

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

However, is this proper to instantiate a class since I am using the static property? How do I gain access to the method if I can't compile time cast it? (System.Object does not have a definition for static MyProperty )

Edit I realized after posting, the class I'm working with is a property, not a method. I apologize for the confusion

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

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

Well, you don't need an instance to call a static method:

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

Is OK... then, simply:

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

should do it.

typeof(Foo<>)
    .MakeGenericType(typeof(string))
    .GetProperty("MyProperty")
    .GetValue(null, null);

You need something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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