请注意,我只展示字符串内容,但实际上可能是任何类型。在每种情况下,我都会说明如何扩展以适用更多值(如果有可能)。
将枚举用作键
您可以将枚举类型用作字典的键(为了唯一性,请将其设置为某个辅助类中的静态和只读属性):
private static readonly Dictionary<MyEnum, string> _dict =
{
{MyEnum.MyValue, "The text for MyValue"},
{MyEnum.MyOtherValue, "Some other text"},
{MyEnum.YetAnotherValue, "Something else"}
}
public static readonly Dictionary<MyEnum, string> Dict
{
get
{
return _dict;
}
}
获取相关联的值:
string text = Dict[MyEnum.MyValue]
或者使用:
string text;
if (Dict.TryGetValue(MyEnum.MyValue, out text))
{
}
else
{
}
通过这种方式,您可以访问与枚举值相关联的字符串。然后,您可以公开您的Dictionary,以便您可以读取相应的值。
如果需要存储多个值,则需要使用复杂类型。只需使用自定义类型而不是字符串即可。或者如果可用,可以使用元组。
访问字典可能意味着额外的麻烦,但希望它也不会意味着线程问题。
Enum.GetName
您可以使用Enum.GetName读取枚举的值的名称:
string text = Enum.GetName(MyEnum.MyValue);
//text will have the text "MyValue"
//or
var some = MyEnum.MyValue;
string text = Enum.GetName(some);
注意:
ToString()
也应该可以工作。
不幸的是,这对于除字符串以外的其他内容将无法起作用。
此外,它的缺点是您无法在那里放置任何文本(它必须是有效的标识符)。
自定义属性
您将需要声明一个属性类型:
[AttributeUsage(AttributeTargets.Field)]
public class EnumValueAttribute : System.Attribute
{
public readonly string _value;
public string Value
{
get
{
return _value;
}
}
public EnumValueAttribute(string value)
{
_value = value;
}
}
现在您需要将此属性应用于您的枚举类型:
public enum MyEnum
{
[EnumValue("The text for MyValue")]
MyValue = 1,
[EnumValue("Some other text")]
MyOtherValue = 2,
[EnumValue("Something else")]
YetAnotherValue = 3
}
最后,您需要读取属性的值:
public static string GetValue(MyEnum enumValue)
{
FieldInfo fieldInfo = typeof(MyEnum).GetField(enumValue.ToString());
if (!ReferenceEquals(fieldInfo, null))
{
object[] attributes = fieldInfo.GetCustomAttributes(typeof(EnumValueAttribute), true);
if (!ReferenceEquals(attributes, null) && attributes.Length > 0)
{
return ((EnumValueAttribute)attributes[0]).Value;
}
}
//Not valid value or it didn't have the attribute
return null;
}
现在你可以称之为:
string text1 = GetValue(MyEnum.MyValue)
//text1 will have the text "MyValue"
//or
var some = MyEnum.MyValue
string text2 = GetValue(some)
您可以向属性类添加更多字段,并使用它们来传递所需的任何其他值。
但这需要反射,并且如果您在沙盒中运行,则可能无法使用。此外,它将每次检索属性,从而在过程中创建一些短暂的对象。
模拟枚举
您可以使用没有公共构造函数并公开其自身的静态只读实例的密封类来模拟枚举:
public sealed class MyEnumEmu
{
private static readonly string myValue = new MyEnumEmu("The text for MyValue");
private static readonly string myOtherValue = new MyEnumEmu("Some other text");
private static readonly string yetAnotherValue = new MyEnumEmu("Something else");
public static MyEnumEmu MyValue
{
get
{
return myValue;
}
}
public static MyEnumEmu MyOtherValue
{
get
{
return myOtherValue;
}
}
public static MyEnumEmu YetAnotherValue
{
get
{
return yetAnotherValue;
}
}
private string _value;
private MyEnumEmu(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
else
{
_value = value;
}
}
public string Value
{
get
{
return _value;
}
}
}
像往常一样使用它:
var some = MyEnumEmu.MyValue
并访问相关值:
string text = MyEnumEmu.MyValue.Value
//text will have the text "MyValue"
//or
string text = some.Value
这是最灵活的选择,您可以使用复杂类型而非字符串或添加额外字段来传递多个值。
但是...它并不是真正的枚举。