我定义了以下枚举。我使用了下划线,因为这个枚举用于日志记录,我不想通过使用自定义属性来招致反射的开销。我们使用非常繁重的日志记录。现在要求是将“LoginFailed_InvalidAttempt1”更改为“LoginFailed Attempt1”。如果我更改此枚举,我将不得不在整个应用程序中更改它的值。我可以用日志记录 SP 中的空格替换下划线。有什么方法可以在不影响整个应用程序的情况下更改它。请提出建议。
public enum ActionType
{
None,
Created,
Modified,
Activated,
Inactivated,
Deleted,
Login,
Logout,
ChangePassword,
ResetPassword,
InvalidPassword,
LoginFailed_LockedAccount,
LoginFailed_InActiveAccount,
LoginFailed_ExpiredAccount,
ForgotPassword,
LoginFailed_LockedAccount_InvalidAttempts,
LoginFailed_InvalidAttempt1,
LoginFailed_InvalidAttempt2,
LoginFailed_InvalidAttempt3,
ForgotPassword_InvalidAttempt1,
ForgotPassword_InvalidAttempt2,
ForgotPassword_InvalidAttempt3,
SessionTimeOut,
ForgotPassword_LockedAccount,
LockedAccount,
ReLogin,
ChangePassword_Due_To_Expiration,
ChangePassword_AutoExpired
}
最佳答案
最好的方法是使用 Description 属性。我知道你不使用反射,但你总是可以缓存结果,这样它只发生一次?
添加描述属性:
[Description("LoginFailed Attempt1")]
LoginFailed_InvalidAttempt1
然后在显示枚举的文本值时,您可以使用以下代码获取描述:
private static Dictionary<Type, Dictionary<Enum, string>> enumMaps = null;
public static string GetDescription(Enum value)
{
Type eType = value.GetType();
if (enumMaps == null)
{
enumMaps = new Dictionary<Type, Dictionary<Enum, string>> ();
}
Dictionary<Enum, string> map;
if (enumMaps.ContainsKey(eType))
{
map = enumMaps[eType];
}
else
{
map = new Dictionary<Enum, string>();
foreach (Enum e in Enum.GetValues(eType))
{
FieldInfo fi = eType.GetField(e.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
map[e] = (attributes.Length > 0) ? attributes[0].Description : e.ToString();
}
enumMaps[eType] = map;
}
return map[value];
}
从上面的代码可以看出,反射只进行了一次。对同一枚举值的任何后续调用都将从闪电般快速的 Dictionary
返回结果。
关于c# - 如何在不影响在 C# 中使用它的客户端的情况下更改枚举定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3037138/