C#——给定一个类的实例,如何访问类的静态成员?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1125647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# -- how does one access a class' static member, given an instance of that class?
提问by JaysonFix
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
?
在 C# 中,假设您有一个对象(比如myObject
),它是 class 的一个实例MyClass
。myObject
仅使用,您将如何访问 的静态成员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
}
}
采纳答案by Jon Skeet
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.
然后你可以使用myObject.Value
来获得正确的值。
回答by Henk Holterman
You simply have to use: MyClass.i
您只需要使用: 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.
但是A.i
和B.i
是完全不同的领域,它们之间没有逻辑关系。即使 B 从 A 继承,反之亦然。
回答by Lou Franco
If you have control of MyClass and need to do this often, I'd add a member property that gives you access.
如果您可以控制 MyClass 并且需要经常这样做,我会添加一个成员属性来让您访问。
class MyClass
{
private static int _i = 123;
public virtual int I => _i;
}