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

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

问题描述

  

可能重复:
  枚举与弦

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

 枚举{名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; }
}

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

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