9

考虑以下类:

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

4

3 回答 3

11

Something like

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

will do. Don't forget to cast to 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.

If you are inside AnotherClass<T> for T = AClass, you can refer to it as T:

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

This will work if you know for sure that your T has static property AProperty. If there is no guarantee that such property exists on any T, you need to check the return values/exceptions on the way.

If only AClass is interesting for you, you can use something like

if (typeof(T) == typeof(AClass))
    n = AClass.AProperty;
else
    ???
于 2012-06-22T14:10:14.903 回答
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为与解决方案无关。

于 2012-06-22T14:14:20.237 回答
0

确保你绑定了你想要的标志 http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags

于 2012-06-22T14:37:58.960 回答