如何通过 C# 中的 Dto 文件返回枚举描述而不是 API 中的名称?

sau*_*rox 1 c# api enums

我有一个名为 FeeNameEnum 的枚举,其中 FeeName 也由说明组成。因此,我尝试在 API 中返回 FeeName 的 FeeName 描述。这是枚举:

public enum FeeNameEnum
{
        [Description("Account Opening Fee (project proponent, General Account holder, Retail Aggregation Account and End User Accoun")]
        AccountOpeningFee,
}
Run Code Online (Sandbox Code Playgroud)

目前,我得到的AccountOpeningFee是 api 响应中的枚举名称。有什么方法可以获取描述而不是枚举名称?

这是我的 Dto 文件代码:

public class FeeScheduleDto
{
        public Guid Id { get; set; }
        public FeeNameEnum FeeName { get; set; }
        public string FeeNameName { get { return FeeName.ToString(); } }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助都会非常明显。

woh*_*tad 6

您可以使用DescriptionAttribute、 fromSystem.ComponentModel来查询枚举值的属性。
下面的代码GetEnumDescription演示了DescriptionAttribute. 它可用于获取任何枚举值的描述​​。如果描述不可用,它也会回退到枚举值本身。

代码示例:

using System;
using System.ComponentModel;
using System.Linq;

public class Program
{
    public static string GetEnumDescription(Enum value)
    {
        if (value == null) { return ""; }

        DescriptionAttribute attribute = value.GetType()
                .GetField(value.ToString())
                ?.GetCustomAttributes(typeof(DescriptionAttribute), false)
                .SingleOrDefault() as DescriptionAttribute;
        return attribute == null ? value.ToString() : attribute.Description;
    }

    public enum FeeNameEnum
    {
        [Description("Account Opening Fee description (...)")]
        AccountOpeningFee,
    }

    public static void Main(String[] args)
    {
        FeeNameEnum e = FeeNameEnum.AccountOpeningFee;
        Console.WriteLine(GetEnumDescription(e));
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Account Opening Fee description (...)
Run Code Online (Sandbox Code Playgroud)

在您的代码中的用法:

在您的实际代码中,您可以添加GetEnumDescription( 和using System.ComponentModel;),然后更改FeeNameName属性:

public string FeeNameName { get { return FeeName.ToString(); } }
Run Code Online (Sandbox Code Playgroud)

到:

public string FeeNameName { get { return GetEnumDescription(FeeName); } }
Run Code Online (Sandbox Code Playgroud)

如果遇到错误,您可以使用此版本,它GetEnumDescription会逐步执行此操作,因此可能有助于确定问题出在哪里:

public static string GetEnumDescription1(Enum value)
{
    if (value == null) { return ""; }

    var type = value.GetType();
    var field = type.GetField(value.ToString());
    var custAttr = field?.GetCustomAttributes(typeof(DescriptionAttribute), false);
    DescriptionAttribute attribute = custAttr?.SingleOrDefault() as DescriptionAttribute;
    return attribute == null ? value.ToString() : attribute.Description;
}
Run Code Online (Sandbox Code Playgroud)

注意:传递给上面参数的参数value应该是一个简单的有效枚举值,或者是一个标志组合 -|多个值的“或”( )。