我如何使用反射调用泛型类的静态属性? [英] How do I call a static property of a generic class with reflection?

查看:212
本文介绍了我如何使用反射调用泛型类的静态属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class Foo< T>我有一个类(我不能修改) {
public static string MyProperty {
get {returnMethod:+ typeof(T).ToString(); }
}
}

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



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

我试过的:

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

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

然而,这是适当的实例化一个类,因为我使用的是静态属性?如果我无法编译时间,如何获得访问方法? (System.Object没有定义静态MyProperty



编辑
我发布后意识到,我正在使用的课程是一种财产,而不是一种方法。我为这种混淆而道歉

解决方案

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

  public class Foo< T> 
{
public static string MyMethod()
{
returnMethod:+ typeof(T).ToString();



类型程序
{
static void Main()
{
类型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);
}
}


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

i.e.

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

这篇关于我如何使用反射调用泛型类的静态属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆