C# 在C web API中定义枚举的显示名称
在我的C web API中,我使用指定的显示名称定义了一个枚举:C# 在C web API中定义枚举的显示名称,c#,angular,enums,C#,Angular,Enums,在我的C web API中,我使用指定的显示名称定义了一个枚举: public enum Countries { Australia, [Display(Name="New Zealand")] NewZealand } 我将这个列表作为字符串列表发送到我的Angular项目,以在下拉菜单中显示它,但我仍然显示了NewZealand。如何将正确的数据发送到Angular项目,而不必在Angular中创建新列表或枚举列表,以避免重复数据,从而在值更改时出现问题
public enum Countries
{
Australia,
[Display(Name="New Zealand")] NewZealand
}
我将这个列表作为字符串列表发送到我的Angular项目,以在下拉菜单中显示它,但我仍然显示了NewZealand。如何将正确的数据发送到Angular项目,而不必在Angular中创建新列表或枚举列表,以避免重复数据,从而在值更改时出现问题
我还尝试了以下代码,得到了相同的结果:
public enum Countries
{
Australia,
[Description("New Zealand")] NewZealand
}
编辑:以下是将我的枚举转换为字符串列表的代码:
public List<string> GetAllCountries()
{
var listOfAllCountries = new List<string>();
foreach (var country in Enum.GetValues(typeof(Countries)))
{
listOfAllCountries.Add(country.ToString());
}
return listOfAllCountries ;
}
答案与以下内容略有不同:
在操作中:请显示创建字符串列表的代码。这是否回答了您的问题?看看这个:-这是对标记的dupe的答案的一个轻微修改。我浏览了Fildor的第一个答案,并尝试了一些建议,但似乎不起作用。出于这样或那样的原因,我无法访问某些方法,如GetDisplayName。我只是想问一下您尝试了什么以及错误是什么。我们可以从那里开始。
using System;
using System.Linq;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
public class Program
{
public static void Main()
{
var names = GetNames();
foreach( var name in names )
Console.WriteLine(name);
}
public static List<string> GetNames()
{
// Convert all values of the enum to their display names
return Enum.GetValues<Countries>().Select(v => v.GetDisplayName()).ToList();
}
}
public enum Countries
{
Australia,
[Display(Name="New Zealand")]
NewZealand,
}
public static class CountriesExtensions
{
public static string GetDisplayName(this Countries enumValue)
{
// If it has a DisplayAttribute, get the name from it:
string name = enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
?.GetName(); // Null-Check!
// No Attribute: Fall back to default.
name = name ?? enumValue.ToString();
}
}