本文介绍了当我只有一个简短的显示名称时,如何获得枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[显示(名称=阿拉巴马州) ,ShortName =AL)]
阿拉巴马= 1,
我只是得到AL从外部数据库。我需要以某种方式阅读我的枚举,并获得适当的价值。感谢任何帮助的人。
解决方案
由于已经给出的答案和一些额外的研究,我想分享我的解决方案作为扩展方法,希望它可以帮助别人:
public static void GetValueByShortName< T> enum e,string shortName,T defaultValue,out T returnValue)
{
returnValue = defaultValue;
var values = from f in typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public)
let attribute = Attribute.GetCustomAttribute(f,typeof(DisplayAttribute))as DisplayAttribute
其中attribute!= null&&& attribute.ShortName == shortName
select(T)f.GetValue(null);
if(values.Count()> 0)
{
returnValue =(T)(object)values.FirstOrDefault();
}
}
您可以使用此扩展名:
var type = MyEnum.Invalid;
type.GetValueByShortName(shortNameToFind,type,out type);
返回类型;
I get a Short Diplay name and i need to get enum value using it?
[Display(Name = "Alabama", ShortName = "AL")]
Alabama = 1,
i just get AL from outside database. I need to read somehow my enum and get a proper value. Thanks for any help guys.
解决方案
Thanks to help from the answers already given and from some additional research, I'd like to share my solution to this as an extension method in hope that it may help others:
public static void GetValueByShortName<T>(this Enum e, string shortName, T defaultValue, out T returnValue)
{
returnValue = defaultValue;
var values = from f in typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public)
let attribute = Attribute.GetCustomAttribute(f, typeof(DisplayAttribute)) as DisplayAttribute
where attribute != null && attribute.ShortName == shortName
select (T)f.GetValue(null);
if (values.Count() > 0)
{
returnValue = (T)(object)values.FirstOrDefault();
}
}
You can use this extension as such:
var type = MyEnum.Invalid;
type.GetValueByShortName(shortNameToFind, type, out type);
return type;
这篇关于当我只有一个简短的显示名称时,如何获得枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!