问题:
I have the following enumeration: 我有以下列举:
public enum AuthenticationMethod
{
FORMS = 1,
WINDOWSAUTHENTICATION = 2,
SINGLESIGNON = 3
}
The problem however is that I need the word "FORMS" when I ask for AuthenticationMethod.FORMS and not the id 1. 但是问题是,当我要求AuthenticationMethod.FORMS而不是ID 1时,我需要单词“ FORMS”。
I have found the following solution for this problem ( link ): 我已经找到以下针对此问题的解决方案( link ):
First I need to create a custom attribute called "StringValue": 首先,我需要创建一个名为“ StringValue”的自定义属性:
public class StringValue : System.Attribute
{
private readonly string _value;
public StringValue(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
Then I can add this attribute to my enumerator: 然后,我可以将此属性添加到我的枚举器中:
public enum AuthenticationMethod
{
[StringValue("FORMS")]
FORMS = 1,
[StringValue("WINDOWS")]
WINDOWSAUTHENTICATION = 2,
[StringValue("SSO")]
SINGLESIGNON = 3
}
And of course I need something to retrieve that StringValue: 当然,我需要一些东西来检索该StringValue:
public static class StringEnum
{
public static string GetStringValue(Enum value)
{
string output = null;
Type type = value.GetType();
//Check first in our cached results...
//Look for our 'StringValueAttribute'
//in the field's custom attributes
FieldInfo fi = type.GetField(value.ToString());
StringValue[] attrs =
fi.GetCustomAttributes(typeof(StringValue),
false) as StringValue[];
if (attrs.Length > 0)
{
output = attrs[0].Value;
}
return output;
}
}
Good now I've got the tools to get a string value for an enumerator. 好了,现在我有了一些工具来获取枚举器的字符串值。 I can then use it like this: 然后,我可以像这样使用它:
string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);
Okay now all of these work like a charm but I find it a whole lot of work. 好的,现在所有这些工作都像是一种魅力,但我发现它完成了很多工作。 I was wondering if there is a better solution for this. 我想知道是否有更好的解决方案。
I also tried something with a dictionary and static properties but that wasn't better either. 我也尝试了一些具有字典和静态属性的方法,但这也不是更好。
解决方案:
参考一: https://stackoom.com/question/1mOc/枚举的字符串表示形式参考二: https://oldbug.net/q/1mOc/String-representation-of-an-Enum
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/4319307