从枚举名称和显示名称

时间:2018-03-16 19:56:43

标签: c# enums

我有一个帮助方法来获取枚举的显示名称:

public static string GetDisplayName(this Enum @enum)
{
    return @enum.GetAttribute<DisplayAttribute>()?.GetName();
}

我试图将枚举名称中的词典作为键,使用此代码将值作为显示名称:

public static Dictionary<string, string> EnumDisplayNameDictionary<TEnum>(this Enum @enum)
{
    var returnDict = new Dictionary<string, string>(); 
    foreach (var item in Enum.GetValues(typeof(TEnum)))
    {
        returnDict.Add(item.ToString(), @enum.GetDisplayName());
    }

    return returnDict;
}

以下是我的一个枚举的代码(包括其所有WCF魔法):

[DataMember]
[Column("cash_revenue_recognition")]
public byte CashRevenueRecognitionId
{
    get
    {
        return (byte)this.CashRevenueRecognition;
    }
    set
    {
        CashRevenueRecognition = (CashRevenueRecognitionChoices) value;
    }
}

[DataMember]
[EnumDataType(typeof(CashRevenueRecognitionChoices))]
public CashRevenueRecognitionChoices CashRevenueRecognition { get; set; }

[DataContract]
[Flags]
public enum CashRevenueRecognitionChoices
{
    [EnumMember]
    [Display(Name ="")]
    NotSet = 0,
    [EnumMember]
    [Display(Name = "When we invoice a customer for their payment")]
    CashAtInvoice = 1,
    [EnumMember]
    [Display(Name = "When we receive a customer payment in our bank account ")]
    CashAtPayment = 2
}

[DataMember]
public Dictionary<string, string> CashEnumDictionary =>
    CashRevenueRecognition.EnumDisplayNameDictionary<CashRevenueRecognitionChoices>();

我遇到的问题是,我不知道如何获取我当前在循环中引用的特定项目的显示名称。

实际输出:

{
    "NotSet" : "When we receive a customer payment in our bank account",
    "CashAtInvoice" : "When we receive a customer payment in our bank account",
    "CashAtPayment" : "When we receive a customer payment in our bank account"
}

预期产出:

{
    "NotSet" : "",
    "CashAtInvoice" : "When we invoice a customer for their payment",
    "CashAtPayment" : "When we receive a customer payment in our bank account"
}

2 个答案:

答案 0 :(得分:1)

在此函数中,Enum.GetValues调用返回一个对象列表,该列表没有GetDisplayName()的定义。

您看到每个对象的相同描述的原因是@enum对象是您用于获取描述的唯一对象

public static Dictionary<string, string> EnumDisplayNameDictionary<TEnum>(this Enum @enum)
{
    var returnDict = new Dictionary<string, string>(); 
    foreach (var item in Enum.GetValues(typeof(TEnum)))
    {
        returnDict.Add(item.ToString(), @enum.GetDisplayName());
    }

    return returnDict;
}

简单地将项目转换为Enum,它将允许您调用GetDisplayName()。

public static Dictionary<string, string> EnumDisplayNameDictionary<TEnum>(this Enum @enum)
{
    var returnDict = new Dictionary<string, string>(); 
    foreach (var item in Enum.GetValues(typeof(TEnum)))
    {
        returnDict.Add(item.ToString(), ((Enum)item).GetDisplayName());
    }

    return returnDict;
}

这样,@enum对象不在此函数中使用,因此可以将其更改为静态函数,而不是扩展函数。

答案 1 :(得分:0)

foreach (var item in Enum.GetValues(typeof(TEnum)))
{
    returnDict.Add(item.ToString(), item.GetDisplayName());
}