C#-给定一个类的实例,如何访问该类的静态成员? [英] C# -- how does one access a class' static member, given an instance of that class?
本文介绍了C#-给定一个类的实例,如何访问该类的静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,假设您有一个作为类MyClass
的实例的对象(例如myObject
).
仅使用myObject
,您将如何访问MyClass
的静态成员?
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
}
}
推荐答案
您将不得不使用反射:
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; } }
}
等
然后,您只需使用myObject.Value
即可获取正确的值.
Then you can just use myObject.Value
to get the right value.
这篇关于C#-给定一个类的实例,如何访问该类的静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文