最初,我希望对枚举进行某种封装,但显然C# 还不可能。我的目的是用枚举存储某种数据。理想情况下,拥有一个对象的枚举会很棒。但显然没有办法做到这一点。因此,我创建了一个状态类、一个公共枚举,并使用一个 setter 创建了一个公共 getter/setter,该 setter 初始化了一个方法,在该方法中我可以将对象作为属性填充。我想知道是否有更好的方法。对我来说理想的解决方案是以正常方式设置状态(枚举):
car.State = CarStates.Idle;
然后像这样访问有关该状态的更多数据:
string message = car.State.Message();
但这将涉及将属性附加到 State 枚举。有什么很酷的技巧可以达到这个效果吗?枚举是您可以通过简单地添加到末尾来制作可切换的、类似单例的值的唯一方法吗?.Idle
这是我现在拥有的代码,它通过添加一个层将状态信息保持在一个级别,这是可以通过的,但在声明类似car.Mode.State = CarModeStates.Idle;
.
class Car
{
public CarState Mode;
public Car()
{
Mode = new CarState();
}
}
class CarState //holds any metadata for given enum value
{
private int _EnumInt;
private string _Message;
private bool _IsError = false;
public CarModeStates State
{
get { return (CarModeStates)_EnumInt; }
set { _EnumInt = (int)value; InitializeState(value); }
}
public string Message { get { return _Message; } }
public bool IsError { get { return _IsError; } }
public void InitializeState(CarModeStates? cs)
{
switch (cs)
{
case (CarModeStates.Off):
{
_Message = "Car is off.";
_IsError = false;
break;
}
case (CarModeStates.Idle):
{
_Message = "Car is idling.";
_IsError = false;
break;
}
case (CarModeStates.Drive):
{
_Message = "Car is driving.";
_IsError = false;
break;
}
case (CarModeStates.Accident):
{
_Message = "CRASH!";
_IsError = true;
break;
}
}
}
}
public enum CarModeStates
{
Off,
Idle,
Drive,
Accident,
}
//And from the outside:
class SomeController
{
Car car = new Car();
public string GetStateMessage()
{
car.Mode.State = CarModeStates.Idle;
return car.Mode.Message;
}
}