如何在 C# 中使用枚举来存储字符串常量? [英] How can I use enum in C# for storing string constants?
问题描述
可能的重复:
带字符串的枚举
枚举中是否可以有如下字符串常量?
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屋!