简体   繁体   中英

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?

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
    ???

First get the generic type of your AnotherClass instance.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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