C# — how does one access a class' static membe

2019-03-27 06:12发布

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

3条回答
时光不老,我们不散
2楼-- · 2019-03-27 06:21

You simply have to use: MyClass.i

To elaborate a little, in order to use a static member, you have to know about the class. And having an object reference is irrelevant. The only way an object would matter is when you would have 2 distinct classes that both have an identical looking member:

class A { public static int i; }
class B { public static int i; }

But A.i and B.i are completely different fields, there is no logical relation between them. Even if B inherits from A or vice versa.

查看更多
贪生不怕死
3楼-- · 2019-03-27 06:26

If you have control of MyClass and need to do this often, I'd add a member property that gives you access.

class MyClass
{
    private static int _i = 123;

    public virtual int I => _i;
}
查看更多
霸刀☆藐视天下
4楼-- · 2019-03-27 06:45

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.

查看更多
登录 后发表回答