使用枚举显示消息框
Use enum to show message boxes
是否可以根据选择的枚举项显示一个MessageBox?例如:
public enum Messages
{
UserAlreadyExists,
NoUserName,
NoPassword,
NoUserNameOrPassword
}
如果是这样,我如何处理每个项目以显示特定的 MessageBox?
尝试以下操作:
switch(input_value)
{
case Messages.UserAlreadyExists:
MessageBox.Show("User already exists");
break;
}
您可以考虑两种替代方法。
显而易见的解决方案:一个简单的 switch 语句:
var msg = Messages.NoPassword;
switch (msg)
{
case Messages.NoPassword:
MessageBox.Show("No password");
break;
case Messages.NoUserName:
MessageBox.Show("No user name");
break;
case Messages.NoUserNameOrPassword:
MessageBox.Show("No user name");
break;
case Messages.UserAlreadyExists:
MessageBox.Show("User already exists");
break;
}
或者,将 [Description] attributes 添加到枚举值(假设枚举未在第三方代码中定义):
MessageBox.Show(GetDescription(msg));
为此你需要 this function:
public static string GetDescription(Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
每个枚举成员都需要修饰:
public enum Messages
{
[Description("User already exists")]
UserAlreadyExists,
[Description("No user name")]
NoUserName,
[Description("No password")]
NoPassword,
[Description("No user name")]
NoUserNameOrPassword
}
当然,这些解决方案都没有本地化。
是否可以根据选择的枚举项显示一个MessageBox?例如:
public enum Messages
{
UserAlreadyExists,
NoUserName,
NoPassword,
NoUserNameOrPassword
}
如果是这样,我如何处理每个项目以显示特定的 MessageBox?
尝试以下操作:
switch(input_value)
{
case Messages.UserAlreadyExists:
MessageBox.Show("User already exists");
break;
}
您可以考虑两种替代方法。
显而易见的解决方案:一个简单的 switch 语句:
var msg = Messages.NoPassword;
switch (msg)
{
case Messages.NoPassword:
MessageBox.Show("No password");
break;
case Messages.NoUserName:
MessageBox.Show("No user name");
break;
case Messages.NoUserNameOrPassword:
MessageBox.Show("No user name");
break;
case Messages.UserAlreadyExists:
MessageBox.Show("User already exists");
break;
}
或者,将 [Description] attributes 添加到枚举值(假设枚举未在第三方代码中定义):
MessageBox.Show(GetDescription(msg));
为此你需要 this function:
public static string GetDescription(Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
每个枚举成员都需要修饰:
public enum Messages
{
[Description("User already exists")]
UserAlreadyExists,
[Description("No user name")]
NoUserName,
[Description("No password")]
NoPassword,
[Description("No user name")]
NoUserNameOrPassword
}
当然,这些解决方案都没有本地化。