我有许多用于错误的枚举,例如:
public enum LoginError
{
None = 0,
InvalidUsername,
InvalidPassword,
}
public enum CustomerError
{
None = 0,
NameRequired,
SurnameRequired,
}
对于每个枚举,我希望将描述存储在列表中,以便我能够做到这样的事情:
string desc = errorList(typeof(LoginError), myError.LoginError); //or something similar
如果我使用多键字典或元组,它会起作用吗?任何显示如何执行此操作的示例?
答案 0 :(得分:3)
我认为这对你有用,
public enum LoginError
{
None = 0,
InvalidUsername,
InvalidPassword,
}
public enum CustomerError
{
None = 0,
NameRequired,
SurnameRequired,
}
private static void Main(string[] args)
{
Dictionary<Enum, string> myErrorDictionary = new Dictionary<Enum, string>();
myErrorDictionary.Add(LoginError.None, "This is None from Login Error");
myErrorDictionary.Add(LoginError.InvalidUsername, "Invalid username");
myErrorDictionary.Add(LoginError.InvalidPassword, "Invalid Password");
myErrorDictionary.Add(CustomerError.None, "This is None from Custom Error");
myErrorDictionary.Add(CustomerError.NameRequired, "Name Required");
myErrorDictionary.Add(CustomerError.SurnameRequired, "Surname Required");
Console.WriteLine(myErrorDictionary[LoginError.None]);
Console.WriteLine(myErrorDictionary[CustomerError.None]);
Console.Read();
}
答案 1 :(得分:0)
您可以使用枚举full name string作为密钥。
Dictionary<string,string> map;
private string GetEnumName(Enum _enum)
{
return string.Format("{0}.{1}", _enum.GetType().Name, _enum.ToString());
}
void RegisterMapping(Enum @enum, string displayName)
{
var enumName= GetEnumName(@enum);
map.Add(enumName, displayName);
}
答案 2 :(得分:0)