繁体   English   中英

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

[英]How can I use Reflection to get the value of a Static Property of a Type without a concrete instance

考虑以下课程:

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的静态值?

就像是

typeof(AClass).GetProperty("AProperty").GetValue(null, null)

会做。 不要忘记转换为int

文档链接: http//msdn.microsoft.com/en-us/library/b05d59ty.aspx (他们也有静态属性的例子。)但是如果你确切地知道AClass ,你可以只使用AClass.AProperty

如果你在T = AClass AnotherClass<T> T = AClass ,你可以将它称为T

typeof(T).GetProperty("AProperty").GetValue(null, null)

如果你确定你的T具有静态属性AProperty ,这将有效。 如果无法保证任何T上存在此类属性,则需要在途中检查返回值/异常。

如果只有AClass对你感兴趣,你可以使用类似的东西

if (typeof(T) == typeof(AClass))
    n = AClass.AProperty;
else
    ???

首先获取您的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删除为与解决方案无关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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