Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 返回枚举名称基值_C#_Asp.net_Foreach_Enums - Fatal编程技术网

C# 返回枚举名称基值

C# 返回枚举名称基值,c#,asp.net,foreach,enums,C#,Asp.net,Foreach,Enums,我有一个枚举 public enum citys { a=1, b=1, c=1, d=2, e=2, f=2, }; 我希望返回基于值的Name。例如,在foreach return Enum.GetNames中,value=1 result --> a,b,c foreach return Enum.GetNames that Value =2 result --> d,e,f 谢谢您的

我有一个枚举

public enum citys
{
       a=1,
       b=1,
       c=1,
       d=2,
       e=2,
       f=2,
};
我希望返回基于值的
Name
。例如,在
foreach return Enum.GetNames
中,
value=1

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

谢谢您的帮助。

您可以将
Enum.GetNames
Enum.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));
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
公共城市
{
a=1,
b=1,
c=1,
d=2,
e=2,
f=2,
}
课堂测试
{
静态void Main()
{
//或GetNames((城市)2)
foreach(GetNames(City.a)中的变量名)
{
Console.WriteLine(名称);
}
}
静态IEnumerable GetNames(T值),其中T:struct
{
返回Enum.GetNames(typeof(T))
其中(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);
}
静态IEnumerable GetNames(T值),其中T:struct
{
返回typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static)
.其中(f=>f.GetValue(null).Equals(value))
.选择(f=>f.Name);
}
对于您想要实现的目标,使用枚举是否是一个好的设计还不是很清楚——这里的真正目标是什么?也许您应该使用查找来代替