从C#的display属性获取枚举名称?

时间:2019-07-09 14:39:53

标签: c# .net-core

我有一个枚举

public enum GTMType
        {
            [Display(Name = "CHANNEL_CHANNEL")]
            ChannelChannel,
            [Display(Name = "CHANNEL_WHOLESALE")]
            ChannelWholesale,
            [Display(Name = "ENTERPRISE_DIRECT")]
            EnterpriseDirect,
            [Display(Name = "ENTERPRISE_AGENT")]
            EnterpriseAgent,
            [Display(Name = "ENTERPRISE_SYSTEM_INTEGRATOR")]
            EnterpriseSystemIntegrator
        }

当我对另一个系统进行API调用以获取数据时,系统将返回显示属性值。

public Account GetDataForAccountByID(string id)
{
  AccountModel accountModel = GetDataFromAnotherSystem(id);
 //after the call is successfull accountModel looks like 
 //{Email: "abc@xyz.com",GTMType:"CHANNEL_CHANNEL"}

 var account = new Account
 {
   EmailAddress: = accountModel.Email,
   GTMType = accountModel.GTMType

 };

}

public class AccountModel
{
public string Email { get; set; }
public string GTMType { get; set; }
}

public class Account
{
    public string EmailAddress { get; set; }
    public GTMType GTMType { get; set; 
 }

如何将具有显示属性值的字符串值转换为枚举。

1 个答案:

答案 0 :(得分:0)

您可以使用Enum.GetValues遍历枚举的可能值,然后使用GetField代表给定值并获取其属性。

GTMType ParseGTMTypeFromAnotherSystem(string gtmType)
{
    var type = typeof(GTMType);

    foreach (var value in Enum.GetValues(type))
    {
        var fieldInfo = type.GetField(Enum.GetName(type, value));
        DisplayAttribute[] attributes = fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false) as DisplayAttribute[];
        if (attributes.Length != 1)
        {
            throw new Exception("Enum definition is wrong.");
        }

        var displayName = attributes[0].Name;
        if (gtmType == displayName)
        {
            return value as GTMType;
        }
    }

    throw new Exception("Unable to parse.");
}

您可能希望以不同的方式处理异常情况,例如如果有多个以上的属性,则对所有DisplayAttribute进行迭代,并忽略不包含任何字段的字段,或者在解析失败的情况下返回默认值-取决于您的用例。