1

最初,我希望对枚举进行某种封装,但显然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;
    }
}
4

6 回答 6

4

您是否尝试过扩展方法?在静态类中,定义:

public static string Message( this CarStates value )
{
    switch (value) {
    ...
    }
}
于 2013-03-10T07:03:11.060 回答
3

C# 中的常规枚举通常不像您的问题所暗示的那样有问题。只需确保您的switch语句有一个default引发 an 的案例,ArgumentException以确保您获得有效值之一。您必须小心字面值0(可以隐式转换为任何枚举类型),但除此之外,enumC# 中的 an 确实在 API 级别提供了实质性的类型安全性。

C# 枚举的性能明显优于 Java 使用的完全封装的枚举。还有一些额外的细节需要注意(例如超出范围的值),但它们在实践中很少引起问题。


Java 风格的枚举类很容易在 C# 中创建。编辑:除了你不能switch像这样在 C# 版本的枚举上使用语句。

  1. 上课sealed
  2. 确保该类至少有 1 个显式构造函数,并确保所有构造函数都是private.
  3. 翻译如下成员:

爪哇:

enum Color { RED, GREEN, BLUE }

C#:

private class Color {
    public static readonly Color RED = new Color();
    public static readonly Color GREEN = new Color();
    public static readonly Color BLUE = new Color();

    private Color() { }
}

如果你真的想模仿Java,你可以通过Enum<T>为这种形式的枚举创建一个抽象基类来保持一个Ordinal属性,并在类中创建一个Values如下所示的静态属性Color

public Color[] Values { get { return new[] { RED, GREEN, BLUE }; } }
于 2013-03-10T06:45:01.203 回答
1

与字典相结合的扩展方法可能是一种解决方案,而不是 switch 语句。

public static class CarExtensionMethods
{
    public static string Message(this CarStates value)
    {
        return carStateDictionary[value];
    }

    private static readonly Dictionary<CarStates, string> carStateDictionary;

    static CarExtensionMethods()
    {
        carStateDictionary = new Dictionary<CarStates, string>();

        carStateDictionary.Add(CarStates.Off, "Car is off.");
        carStateDictionary.Add(CarStates.Idle, "Car is idling.");
        carStateDictionary.Add(CarStates.Drive, "Car is driving.");
        carStateDictionary.Add(CarStates.Accident, "CRASH!");
    }
}

用法非常简单:

CarStates state = CarState.Idle;
Console.WriteLine(state.Message());  //writes "Car is idling."

同样作为旁注,通常名称只有在具有属性enum时才应该是复数。[Flags]关键是表明它们可以有多个状态。一个更适合您的枚举的名称是CarState因为它一次不能有多个状态。

于 2013-03-10T07:20:26.900 回答
1

如果您只想使用Enum值,那么您可以创建自己的属性来提供额外的元数据。

下面的示例有效,但我个人不会以这种方式对我的域进行建模。

// sample test app
class Program
{
    static void Main(string[] args)
    {
        var carState = CarModeStates.Accident;

        // the call to get the meta data could and probably should be stored in a local variable
        Console.WriteLine(carState.GetMetaData().Message);
        Console.WriteLine(carState.GetMetaData().IsError);
        Console.WriteLine(carState.GetMetaData().IsUsingPetrol);
        Console.Read();
    }
}

扩展枚举示例

// enum with meta data
public enum CarModeStates
{
    [CarStatus("Car is off."), IsError(false), IsUsingPetrol(false)]
    Off,

    [CarStatus("Car is idling."), IsError(false), IsUsingPetrol(true)]
    Idle,

    [CarStatus("Car is driving."), IsError(false), IsUsingPetrol(true)]
    Drive,

    [CarStatus("CRASH!"), IsError(true), IsUsingPetrol(false)]
    Accident
}

自定义属性来装饰枚举

public interface IAttribute<out T>
{
    T Description { get; }
}

[AttributeUsage(AttributeTargets.Field)]
public class CarStatusAttribute : Attribute, IAttribute<string>
{
    private readonly string _value;

    public CarStatusAttribute(string value)
    {
        _value = value;
    }

    public string Description
    {
        get { return _value; }
    }
}

[AttributeUsage(AttributeTargets.Field)]
public class IsErrorAttribute : Attribute, IAttribute<bool>
{
    private readonly bool _value;

    public IsErrorAttribute(bool value)
    {
        _value = value;
    }

    public bool Description
    {
        get { return _value; }
    }
}

[AttributeUsage(AttributeTargets.Field)]
public class IsUsingPetrolAttribute : Attribute, IAttribute<bool>
{
    private readonly bool _value;

    public IsUsingPetrolAttribute(bool value)
    {
        _value = value;
    }

    public bool Description
    {
        get { return _value; }
    }
}

用于获取有关枚举的元数据的扩展方法。

public static class CarModeStatesExtensions
{
    public static CarModeStateModel GetMetaData(this CarModeStates value)
    {
        var model = new CarModeStateModel
            {
                Message = value.GetDescriptionFromEnumValue<string>(typeof (CarStatusAttribute)),
                IsError = value.GetDescriptionFromEnumValue<bool>(typeof(IsErrorAttribute)),
                IsUsingPetrol = value.GetDescriptionFromEnumValue<bool>(typeof (IsUsingPetrolAttribute))
            };

        return model;
    }
}

public class CarModeStateModel
{
    public string Message { get; set; }
    public bool IsError { get; set; }
    public bool IsUsingPetrol { get; set; }
}

public static class EnumExtensions
{
    public static T GetDescriptionFromEnumValue<T>(this CarModeStates value, Type attributeType)
    {
        var attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(attributeType, false).SingleOrDefault();

        if (attribute == null)
        {
            return default(T);
        }

        return ((IAttribute<T>)attribute).Description;
    }
}
于 2013-03-10T07:28:08.120 回答
1

也许你需要一个这样的“工厂”:

public class CarState
{
    private string message;
    private bool error;

    public CarState(string message, bool error)
    {
        this.message = message;
        this.error = error;
    }

    public string Message
    {
        get { return this.message; }
    }

    public bool Error
    { 
        get { return this.error; }
    }
}

public static class CarStateFactory
{
    public enum CarStateId { Off, Idle, Driving, Accident }

    public static CarState GetCarState(CarStateId carStateId)
    {
        switch(carStateId)
        {
            case (CarStateId.Off):
                { return new CarState("Car is off", false); }

            //add more cases

            default:
                return null;
        }
    }
}

有了这个,你可以通过调用来设置你的汽车的状态:

car.State = CarStateFactory.GetCarState(CarStateFactory.ID.Off); //ID.Idle, ID.Driving, ID.Accident

您可以使用 访问该消息car.State.Message

编辑: CarStateFactory 的静态吸气剂

public static CarState Idle
{
    get
    {
        return new CarState("Car is off", false);
    }
}
于 2013-03-10T07:58:44.943 回答
0

我知道这已经很老了,但是对于更多的访问者来说,而不是为此使用枚举,也许使用状态管理器,其中一个对象代表每个状态?

抽象的

/// <summary>
/// Defines the expected members of a state
/// </summary>
internal interface ICarState
{
    /// <summary>
    /// Gets or sets the message.
    /// </summary>
    /// <value>
    /// The message.
    /// </value>
    string Message { get; }
}

基础状态

/// <summary>
/// The class that all car states should inherit from.
/// </summary>
internal abstract class CarBaseState : ICarState
{
    #region ICarState Members

    /// <summary>
    /// Gets or sets the message.
    /// </summary>
    /// <value>
    /// The message.
    /// </value>
    /// </exception>
    public abstract string Message { get; }

    #endregion
}

执行

/// <summary>
/// Represents the state when the car is off
/// </summary>
internal class OffState : CarBaseState
{
    /// <summary>
    /// Gets or sets the message.
    /// </summary>
    /// <value>
    /// The message.
    /// </value>
    /// </exception>
    public override string Message { get { return "Off"; } }
}

/// <summary>
/// Represents the state when the car is idling
/// </summary>
internal class IdleState : CarBaseState
{
    /// <summary>
    /// Gets or sets the message.
    /// </summary>
    /// <value>
    /// The message.
    /// </value>
    /// </exception>
    public override string Message { get { return "Idling"; } }
}

经理

internal class CarStateManager
{
    #region Fields

    Dictionary<string, ICarState> _stateStore = null;

    #endregion

    #region Properties

    /// <summary>
    /// Gets (or privately sets) the state of the current.
    /// </summary>
    /// <value>
    /// The state of the current.
    /// </value>
    internal ICarState CurrentState { get; private set;  }

    #endregion

    #region Constructors and Initialisation

    /// <summary>
    /// Initializes a new instance of the <see cref="StateManager"/> class.
    /// </summary>
    public CarStateManager()
    {
        _stateStore = new Dictionary<string, ICarState>();
    }

    #endregion

    #region Methods

    /// <summary>
    /// Adds a state.
    /// </summary>
    /// <param name="stateId">The state identifier.</param>
    /// <param name="state">The state.</param>
    public void AddState(string stateId, ICarState state)
    {
        // Add the state to the collection
        _stateStore.Add(stateId, state);
    }

    /// <summary>
    /// Changes the state.
    /// </summary>
    /// <param name="stateId">The state identifier.</param>
    public void ChangeState(string stateId)
    {

        // Set thr current state
        CurrentState = _stateStore[stateId];
    }

    #endregion
}

程序

class Program
{
    internal class StateKeys
    {
        public const string Off = "Off";
        public const string Idle = "Idle";
    }

    static void Main(string[] args)
    {
        // Instantiate the state manager
        CarStateManager stateManager = new CarStateManager();

        // Add the states
        stateManager.AddState(StateKeys.Off, new OffState());
        stateManager.AddState(StateKeys.Idle, new IdleState());

        // Change the state and display the message
        stateManager.ChangeState(StateKeys.Off);
        Console.WriteLine(stateManager.CurrentState.Message);

        // Change the state and display the message
        stateManager.ChangeState(StateKeys.Idle);
        Console.WriteLine(stateManager.CurrentState.Message);
        Console.ReadLine();
    }
}

输出:

Off
Idling

于 2015-01-19T07:49:39.477 回答