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?
To set property values via Reflection, you must use the Type. GetProperty() method, then invoke the PropertyInfo. SetValue() method. The default overload that we used accepts the object in which to set the property value, the value itself, and an object array, which in our example is null.
A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name.
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
???
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With