[英]Static enum class member
Can I declare my enum
as a static member inside another class? 我可以将我的
enum
声明为另一个类中的静态成员吗? I want only one instance from this enum 我只需要这个枚举中的一个实例
public enum MyEnum
{
Add,
Remove
}
public class MyClass
{
private static MyEnum _myEnum;
public MyEnum Enum
{
get { return _myEnum; }
set { _myEnum = value; }
}
}
Is it Ok to do that? 这样可以吗?
I would strongly suggest to make also the property static
since it's pointless to get/set a static field from a non-static property. 我强烈建议将属性也设为
static
因为从非静态属性获取/设置静态字段毫无意义。
That's not only confusing. 这不仅令人困惑。 I would call that begging for bugs.
我称呼乞讨的错误。
Consider this: 考虑一下:
var c1 = new MyClass { Enum = MyEnum.Add };
var c2 = new MyClass { Enum = MyEnum.Add };
c2.Enum = MyEnum.Remove;
Console.Write(c1.Enum.ToString());
What do you expect as output? 您期望输出什么? Both instances now have
MyEnum.Remove
even if i only set one. 现在两个实例都具有
MyEnum.Remove
即使我只设置了一个。
If you make it static above would not even compile which is a good thing. 如果在上面将其设置为静态,则什至不会编译,这是一件好事。
You would need to use the property via classname which shows clearly that it`sa static property: 您需要通过类名使用该属性,该名称清楚地表明它是静态属性:
MyClass.Enum = MyEnum.Remove;
Define your property as static
too 也将属性定义为
static
public static MyEnum Enum
{
get { return _myEnum; }
set { _myEnum = value; }
}
It is totally okey asuming you will only access it through created MyClass objects. 假设您只能通过创建的MyClass对象访问它,这是完全好的。 If you want to be able to set or get Enum without an instantiated object, IE make Enum a singleton just as _myEnum, you should declare it static.
如果希望能够在没有实例化对象的情况下设置或获取Enum,则IE就像_myEnum一样将Enum设为单例,则应将其声明为静态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.