c#:如何使用枚举存储字符串常量? [英] c#:How to use enum for storing string constants?

查看:141
本文介绍了c#:如何使用枚举存储字符串常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

带有字符串的枚举


可以在枚举中具有字符串常量,如

 枚举{name1 =hmmmname2 =bdidwe} 

如果不是这样做最好的方法?



我试过它不适用于字符串,所以现在我分组所有一个类中的相关常量,如

 类操作
{
public const string name1 =hmmm;
public const string name2 =bdidwe
}


解决方案

枚举常数只能是顺序类型(默认情况下为 int ),因此您不能在枚举中使用字符串常量。



当我想要一个类似基于字符串的枚举时,我创建一个类来保存常量,除了我做一个静态类以防止不必要的实例化和不必要的子类化。 / p>

但是如果您不想使用字符串作为方法签名中的类型,并且您更喜欢使用更安全,更严格的类型(例如操作),您可以使用安全的枚举模式:

 公开密封的类操作
{
public static readonly操作名称1 =新操作(Name1);
public static readonly操作Name2 = new操作(Name2);

private操作(字符串值)
{
Value = value;
}

public string Value {get;私人集合}
}


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

这篇关于c#:如何使用枚举存储字符串常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆