gpt4 book ai didi

c# - 返回枚举名称基值

转载 作者:行者123 更新时间:2023-12-02 05:00:25 24 4
gpt4 key购买 nike

我有一个枚举

public enum citys
{
a=1,
b=1,
c=1,
d=2,
e=2,
f=2,
};

我想根据值返回 Name。例如,在 foreach return Enum.GetNamesValue =1

 result --> a,b,c
foreach return Enum.GetNames that Value =2
result --> d,e,f

感谢您的帮助。

最佳答案

好吧,您可以将 Enum.GetNamesEnum.Parse 结合使用 - 这不是我喜欢做的事情,但它作品:

using System;
using System.Collections.Generic;
using System.Linq;

public enum City
{
a=1,
b=1,
c=1,
d=2,
e=2,
f=2,
}

class Test
{
static void Main()
{
// Or GetNames((City) 2)
foreach (var name in GetNames(City.a))
{
Console.WriteLine(name);
}
}

static IEnumerable<string> GetNames<T>(T value) where T : struct
{
return Enum.GetNames(typeof(T))
.Where(name => Enum.Parse(typeof(T), name).Equals(value));
}
}

或者,您可以通过反射获取字段:

static IEnumerable<string> GetNames<T>(T value) where T : struct
{
return typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(f => f.GetValue(null).Equals(value))
.Select(f => f.Name);
}

虽然对于您想要实现的目标而言,使用枚举是否是一个好的设计并不是很清楚 - 这里的真正目标是什么?也许您应该改用查找?

关于c# - 返回枚举名称基值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17185152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com