如何使用枚举来存储string常量?

可能重复:
枚举与string

有可能在枚举中有string常量

enum{name1="hmmm" name2="bdidwe"} 

如果不是这样做最好的办法是什么?

我试过它不工作的string,所以现在我将所有相关的常量分组在一个类中

  class operation { public const string name1="hmmm"; public const string name2="bdidwe" } 

枚举常量只能是序数types(默认为int ),所以你不能在枚举中使用string常量。

当我想要一个像“基于string的枚举”的东西时,我创build了一个类来容纳像你所做的常量,除了我使它成为一个静态类,以防止不想要的实例化和不需要的子类。

但是,如果您不想在方法签名中使用string作为types,并且您更喜欢更安全,更严格的types(如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; } } 

您可以使用DescriptionAttribute来完成此操作,但是您必须编写代码才能使string脱离属性。

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

枚举的整个点是序数常量。
但是,您可以使用扩展方法来实现您想要的function:

  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(); 

您的operation类不会按原样编译…您没有声明name1和name2的types…

但是,这是我采取的方法…是的。

如果你使它成为一个结构,那么它就变成了一个值types,它可能是也可能不是你想要的。