In C#, suppose you have an object (say, myObject
) that is an instance of class MyClass
.
Using myObject
only, how would you access a static member of MyClass
?
class MyClass
{
public static int i = 123 ;
}
class MainClass
{
public static void Main()
{
MyClass myObject = new MyClass() ;
myObject.GetType().i = 456 ; // something like this is desired,
// but erroneous
}
}
You'd have to use reflection:
Type type = myObject.GetType();
FieldInfo field = type.GetField("i", BindingFlags.Public |
BindingFlags.Static);
int value = (int) field.GetValue(null);
I'd generally try to avoid doing this though... it's very brittle. Here's an alternative using normal inheritance:
public class MyClass
{
public virtual int Value { get { return 10; } }
}
public class MyOtherClass : MyClass
{
public override int Value { get { return 20; } }
}
etc.
Then you can just use myObject.Value
to get the right value.