我计划使用Enum填写国家列表下拉列表。所以我需要枚举值描述和该索引值。 我的条件:
我的枚举:
public enum CountryListEnum
{
[Description("United Kingdom")]
UnitedKingdom = 0,
[Description("United States")]
UnitedStates = 1,
[Description("Afghanistan")]
Afghanistan = 2,
[Description("Albania")]
Albania = 3,
}
我的模特:
public class CountryModel
{
public int CountryId { get; set; }
public string CountryName { get; set; }
}
答案 0 :(得分:1)
要获取索引值,只需将枚举转换为int即可。获取description属性要稍微复杂一些。也许像这样
public enum CountryListEnum
{
[Description("United Kingdom")]
UnitedKingdom = 0,
[Description("United States")]
UnitedStates = 1,
[Description("Afghanistan")]
Afghanistan = 2,
[Description("Albania")]
Albania = 3,
}
static void Main(string[] args)
{
foreach (var country in Enum.GetValues(typeof(CountryListEnum)).Cast<CountryListEnum>())
{
Console.WriteLine($"Index: {(int)country}");
Console.WriteLine($"Description: {GetDescription(country)}");
}
}
public static string GetDescription(Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
System.Reflection.FieldInfo field = type.GetField(name);
if (field != null)
{
if (Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) is DescriptionAttribute attr)
{
return attr.Description;
}
}
}
return null;
}
答案 1 :(得分:0)
我认为这应该对您的实施有所帮助。
foreach (var item in Enum.GetValues(typeof(CountryListEnum)))
{
CountryModel myModel = new CountryModel();
myModel.CountryId = item.GetHashCode();
myModel.CountryName = item.ToString();
}
修改
正如其他人指出的那样,以上内容将不会检索描述。这是有关如何实现描述属性重试的更新。
foreach (var item in Enum.GetValues(typeof(CountryListEnum)))
{
CountryModel myModel = new CountryModel();
myModel.CountryId = item.GetHashCode();
var type = typeof(CountryListEnum);
var memInfo = type.GetMember(item.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
var description = ((DescriptionAttribute)attributes[0]).Description;
myModel.CountryName = description;
}
答案 2 :(得分:0)
我认为,这就是您想要的。
var model = new List<CountryModel>();
foreach (var item in Enum.GetValues(typeof(CountryListEnum)))
{
model.Add(new CountryModel
{
CountryId = (int)item,
CountryName = ((DescriptionAttribute)item.GetType().GetField(item.ToString()).GetCustomAttribute(typeof(DescriptionAttribute), false)).Description
});
}