enum MyEnum
{
FirstValue, //Default Value will be 0
SecondValue, // 1
ThirdValue // 2
}
string str1 = Enum.GetName(typeof(MyEnum), 0); //will return FirstValue
string str2 = Enum.GetName(typeof(MyEnum), MyEnum.SecondValue); //SecondValue
如果您需要像空格等完整字符串,您需要通過添加描述方法。 否則我推薦創建一個查找字典。
string value = MyLookupTable.GetValue(1); // First Value
value = MyLookupTable.GetValue(2); // Second Value
value = MyLookupTable.GetValue(3); // Third Value
class MyLookupTable
{
private static Dictionary<int, string> lookupValue = null;
private MyLookupTable() {}
public static string GetValue(int key)
{
if (lookupValue == null || lookupValue.Count == 0)
AddValues();
if (lookupValue.ContainsKey(key))
return lookupValue[key];
else
return string.Empty; // throw exception
}
private static void AddValues()
{
if (lookupValue == null)
{
lookupValue = new Dictionary<int, string>();
lookupValue.Add(1, "First Value");
lookupValue.Add(2, "Second Value");
lookupValue.Add(3, "Third Value");
}
}
}
http://stackoverflow.com/questions/3501966/enums-with-string-values-and-finding-enum-by-value?rq=1 –
你想,對於什麼? –
@RaphaelAlthaus:你會發布這個答案嗎? – Breeze