c#:如何使用枚举来存储字符串常量?

Mad*_*hik 54 .net string enums constants

可能重复:
带字符串的枚举

可以在枚举中使用字符串常量

      enum{name1="hmmm" name2="bdidwe"}
Run Code Online (Sandbox Code Playgroud)

如果不是这样,最好的方法是什么?

我试过它不能用于字符串所以现在我将所有相关的constnats分组在一个类中

      class operation
      {
          public const string  name1="hmmm";
          public const string  name2="bdidwe"
      }
Run Code Online (Sandbox Code Playgroud)

R. *_*des 105

枚举常量只能是序数类型(int默认情况下),因此您不能在枚举中包含字符串常量.

当我想要像"基于字符串的枚举"之类的东西时,我创建了一个类来保存常量,就像你做的那样,除了我使它成为一个静态类,以防止不必要的实例化和不需要的子类化.

但是,如果您不想使用字符串作为方法签名中的类型,并且您更喜欢更安全,更具限制性的类型(如Operation),则可以使用安全枚举模式:

public sealed class Operation
{
    public static readonly Operation Name1 = new Operation("Name1");
    public static readonly Operation Name2 = new Operation("Name2");

    private Operation(string value)
    {
        Value = value;
    }

    public string Value { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

  • +1适合完美.添加到隐式操作,你就是黄金:`public static implicit operator string(Operation op){return op.Value; 因为那时你可以将它用作强类型参数或字符串. (21认同)
  • 但在需要字符串常量的地方,例如在 switch..case 语句中,不可能使用上述模式 (2认同)

Tay*_*ese 40

你可以使用DescriptionAttribute,但是你必须编写代码来从属性中获取字符串.

public enum YourEnum
{
    [Description("YourName1")]
    Name1,

    [Description("YourName2")]
    Name2
}
Run Code Online (Sandbox Code Playgroud)

  • +1第一次遇到Description属性.谢谢 :) (3认同)

Rob*_*cke 9

枚举的全部要点是序数常数.
但是,您可以使用扩展方法实现所需的目标:

  enum Operation
  {
      name1,
      name2
  }

  static class OperationTextExtender
  {
        public static String AsText(this Operation operation)
        {
              switch(operation)
              {
                    case Operation.name1: return "hmmm";
                    case Operation.name2: return "bdidwe";
                    ...
              }
        }
  }

  ...
  var test1 = Operation.name1;
  var test2 = test1.AsText();   
Run Code Online (Sandbox Code Playgroud)