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

2023-09-02 11:51:30 作者:痛定思痛。

可能重复:   枚举与弦

时,可以有枚举字符串常量像

 枚举{名1 =嗯名称2 =bdidwe}
 

如果它不是那么什么是这样做的最好方法是什么?

我试了一下它不工作的字符串,所以现在我的分组在一个类中的所有相关constnats像

 类操作
      {
          公共常量字符串名称1 =嗯;
          公共常量字符串名称2 =bdidwe
      }
 
使用字符串常量作右值 作函数调用时的实际参数,取用的是字符串对应存储空间的

解决方案

枚举常量只能是序数类型(int 默认),所以你不能有字符串常量的枚举。

当我想要的东西就像一个基于字符串的枚举我创建一个类像你一样保持常量,但我做一个静态类prevent既不必要的实例化和不必要的子类。

但是,如果你不想使用字符串作为方法签名的类型和preFER一个更安全,更严格的类型(如工作),你可以使用安全枚举模式:

 公共密封类操作
{
    公共静态只读操作名称1 =新的操作(名称1);
    公共静态只读操作名称2 =新的操作(名称2);

    私人操作(字符串值)
    {
        值=价值;
    }

    公共字符串值{获得;私定; }
}
 

Possible Duplicate: Enum with strings

is is possible to have string constants in enum like

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

if it is not so what is best way to do so?

I tried it its not working for string so right now i am grouping all related constnats in one class like

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

解决方案

Enum constants can only be of ordinal types (int by default), so you can't have string constants in enums.

When I want something like a "string-based enum" I create a class to hold the constants like you did, except I make it a static class to prevent both unwanted instantiation and unwanted subclassing.

But if you don't want to use string as the type in method signatures and you prefer a safer, more restrictive type (like Operation), you can use the safe enum pattern:

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; }
}