如何在C#中使用枚举存储字符串常量? [英] How can I use enum in C# for storing string constants?

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

问题描述

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

Possible Duplicate:
Enum with strings

是否可以像下面这样在枚举中包含字符串常量?

Is it possible to have string constants in enum like the following?

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

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

If it is not, what is the best way to do so?

我尝试过,但是它不适用于字符串,所以现在我将所有相关的常量归为一个类,

I tried it, but it's not working for string so right now I am grouping all related constants in one class like

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

推荐答案

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

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.

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

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天全站免登陆