考虑以下课程:
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的静态值?
答案 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)