[英]How can I use Reflection to get the value of a Static Property of a Type without a concrete instance
Consider the following class: 考虑以下课程:
public class AClass : ISomeInterface
{
public static int AProperty
{
get { return 100; }
}
}
I then have another class as follows: 然后我有另一个课程如下:
public class AnotherClass<T>
where T : ISomeInterface
{
}
Which I instance via: 我通过以下方式实例:
AnotherClass<AClass> genericClass = new AnotherClass<AClass>();
How can I get the static value of AClass.AProperty from within my genericClass without having a concrete instance of AClass? 如何在没有具体的AClass实例的情况下从我的genericClass中获取AClass.AProperty的静态值?
Something like 就像是
typeof(AClass).GetProperty("AProperty").GetValue(null, null)
will do. 会做。 Don't forget to cast to int
. 不要忘记转换为int
。
Documentation link: http://msdn.microsoft.com/en-us/library/b05d59ty.aspx (they've got example with static properties, too.) But if you know exactly AClass
, you can use just AClass.AProperty
. 文档链接: http : //msdn.microsoft.com/en-us/library/b05d59ty.aspx (他们也有静态属性的例子。)但是如果你确切地知道AClass
,你可以只使用AClass.AProperty
。
If you are inside AnotherClass<T>
for T = AClass
, you can refer to it as T
: 如果你在T = AClass
AnotherClass<T>
T = AClass
,你可以将它称为T
:
typeof(T).GetProperty("AProperty").GetValue(null, null)
This will work if you know for sure that your T
has static property AProperty
. 如果你确定你的T
具有静态属性AProperty
,这将有效。 If there is no guarantee that such property exists on any T
, you need to check the return values/exceptions on the way. 如果无法保证任何T
上存在此类属性,则需要在途中检查返回值/异常。
If only AClass
is interesting for you, you can use something like 如果只有AClass
对你感兴趣,你可以使用类似的东西
if (typeof(T) == typeof(AClass))
n = AClass.AProperty;
else
???
First get the generic type of your AnotherClass
instance. 首先获取您的AnotherClass
实例的泛型类型。
Then get the static property. 然后获取静态属性。
Then get the property's static value. 然后获取属性的静态值。
// 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);
}
}
Recognizing, of course, that it isn't possible to ensure that "AProperty" will exist, because interfaces don't work on static signatures, I removed ISomeInterface
as being irrelevant to the solution. 当然,认识到不可能确保存在“AProperty”,因为接口不能用于静态签名,我将ISomeInterface
删除为与解决方案无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.