如何在没有具体实例的情况下使用Reflection来获取Type的静态属性的值

时间:2012-06-22 14:06:36

标签: c# asp.net generics reflection

考虑以下课程:

public class AClass : ISomeInterface
{
    public static int AProperty
    {
   get { return 100; } 
    }
}

然后我有另一个课程如下:

public class AnotherClass<T>
   where T : ISomeInterface
{

}

我通过以下实例:

AnotherClass<AClass> genericClass = new  AnotherClass<AClass>();

如何在没有具体的AClass实例的情况下从genericClass中获取AClass.AProperty的静态值?

3 个答案:

答案 0 :(得分:10)

这样的东西
typeof(AClass).GetProperty("AProperty").GetValue(null, null)

会做的。不要忘记施放到int

文档链接:http://msdn.microsoft.com/en-us/library/b05d59ty.aspx(他们也有静态属性示例。)但如果您确切知道AClass,则只能使用AClass.AProperty

如果您位于AnotherClass<T>的{​​{1}}内,则可以将其称为T = AClass

T

如果您确定typeof(T).GetProperty("AProperty").GetValue(null, null) 具有静态属性T,这将有效。如果无法保证任何AProperty上存在此类属性,则需要在途中检查返回值/例外情况。

如果只有T对你感兴趣,你可以使用类似

的内容
AClass

答案 1 :(得分:1)

首先获取AnotherClass实例的泛型类型。

然后获取静态属性。

然后获取属性的静态值。

// I made this sealed to ensure that `this.GetType()` will always be a generic
// type of `AnotherClass<>`.
public sealed class AnotherClass<T>
{
    public AnotherClass(){
        var aPropertyValue = ((PropertyInfo)
                this.GetType()
                    .GetGenericArguments()[0]
                    .GetMember("AProperty")[0])
            .GetValue(null, null);
    }
}

当然认识到,不可能确保“AProperty”存在,因为接口不适用于静态签名,我将ISomeInterface删除为与解决方案无关。

答案 2 :(得分:0)