Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.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#_.net_Enums - Fatal编程技术网

C# 将枚举集合转换为给定类型的字典

C# 将枚举集合转换为给定类型的字典,c#,.net,enums,C#,.net,Enums,我希望创建一个函数,将枚举转换为字典列表。枚举名称也将转换为更易于阅读的形式。我只想调用函数,提供枚举类型,然后取回字典。我相信我就快到了,我只是想不出如何将枚举强制转换为正确的类型。(在“returnList.Add”行中获取错误)。现在我只是对类型使用var,但是我知道类型,因为它是传入的 internal static Dictionary<int,string> GetEnumList(Type e) { List<string> exclusionLis

我希望创建一个函数,将枚举转换为字典列表。枚举名称也将转换为更易于阅读的形式。我只想调用函数,提供枚举类型,然后取回字典。我相信我就快到了,我只是想不出如何将枚举强制转换为正确的类型。(在“returnList.Add”行中获取错误)。现在我只是对类型使用var,但是我知道类型,因为它是传入的

internal static Dictionary<int,string> GetEnumList(Type e)
{
    List<string> exclusionList =
    new List<string> {"exclude"};

    Dictionary<int,string> returnList = new Dictionary<int, string>();

    foreach (var en in Enum.GetValues(e))
    {
        // split if necessary
        string[] textArray = en.ToString().Split('_');

        for (int i=0; i< textArray.Length; i++)
        {
            // if not in the exclusion list
            if (!exclusionList
                .Any(x => x.Equals(textArray[i],
                    StringComparison.OrdinalIgnoreCase)))
            {
                textArray[i] = Thread.CurrentThread.CurrentCulture.TextInfo
                    .ToTitleCase(textArray[i].ToLower());
            }
        }

        returnList.Add((int)en, String.Join(" ", textArray));
    }

    return returnList;
}
内部静态字典GetEnumList(类型e)
{
排除名单=
新列表{“排除”};
Dictionary returnList=新字典();
foreach(Enum.GetValues(e)中的var en)
{
//必要时分开
字符串[]textArray=en.ToString().Split(“”);
for(int i=0;ix.Equals)(textary[i],
StringComparison.OrdinalIgnoreCase(参考文献1)
{
textArray[i]=Thread.CurrentThread.CurrentCulture.TextInfo
.ToTitleCase(textary[i].ToLower());
}
}
Add((int)en,String.Join(“,textArray));
}
退货清单;
}

您可以使用泛型方法,该方法将创建包含枚举值和名称的字典:

public static Dictionary<int, string> GetEnumList<T>()
{
    Type enumType = typeof(T);
    if (!enumType.IsEnum)
        throw new Exception("Type parameter should be of enum type");

    return Enum.GetValues(enumType).Cast<int>()
               .ToDictionary(v => v, v => Enum.GetName(enumType, v));
}
公共静态字典GetEnumList()
{
类型enumType=typeof(T);
如果(!enumType.IsEnum)
抛出新异常(“类型参数应为枚举类型”);
返回Enum.GetValues(enumType.Cast())
.ToDictionary(v=>v,v=>Enum.GetName(enumType,v));
}
您可以根据需要修改默认的枚举名称。用法:

var daysDictionary = Extensions.GetEnumList<DayOfWeek>();
string monday = daysDictionary[1];
var daysDictionary=Extensions.GetEnumList();
字符串monday=daysDictionary[1];

请注意,使用enum(C#)定义的类型可以有多种底层类型(byte、sbyte、short、ushort、int、uint、long、ulong),如文档所述:。这意味着并非所有的枚举值都可以安全地强制转换为int,并且可以在不抛出异常的情况下逃之夭夭

例如,如果希望进行泛化,可以安全地将所有枚举值强制转换为float(尽管很奇怪,但它涵盖了所有枚举的底层类型)。或者您可以通过泛型请求特定的底层类型

这两种解决方案都不是完美的,尽管它们都通过充分的参数验证安全地完成了工作。浮点值解决方案的泛化:

static public IDictionary<float, string> GetEnumList(Type enumType)
{
    if (enumType != null)
        if (enumType.IsEnum)
        {
            IDictionary<float, string> enumList = new Dictionary<float, string>();

            foreach (object enumValue in Enum.GetValues(enumType))
                enumList.Add(Convert.ToSingle(enumValue), Convert.ToString(enumValue));

            return enumList;
        }
        else
            throw new ArgumentException("The provided type is not an enumeration.");
    else
        throw new ArgumentNullException("enumType");
}
static public IDictionary<EnumUnderlyingType, string> GetEnumList<EnumUnderlyingType>(Type enumType)
{
    if (enumType != null)
        if (enumType.IsEnum && typeof(EnumUnderlyingType) == Enum.GetUnderlyingType(enumType))
        {
            IDictionary<EnumUnderlyingType, string> enumList = new Dictionary<EnumUnderlyingType, string>();

            foreach (object enumValue in Enum.GetValues(enumType))
                enumList.Add((EnumUnderlyingType)enumValue, enumValue.ToString());

            return enumList;
        }
        else
            throw new ArgumentException("The provided type is either not an enumeration or the underlying type is not the same with the provided generic parameter.");
    else
        throw new ArgumentNullException("enumType");
}
静态公共IDictionary GetEnumList(类型enumType)
{
if(枚举类型!=null)
if(enumType.IsEnum)
{
IDictionary enumList=新字典();
foreach(枚举中的对象枚举值。GetValues(枚举类型))
Add(Convert.ToSingle(enumValue)、Convert.ToString(enumValue));
返回枚举列表;
}
其他的
抛出新ArgumentException(“提供的类型不是枚举”);
其他的
抛出新ArgumentNullException(“enumType”);
}
通用参数解决方案:

static public IDictionary<float, string> GetEnumList(Type enumType)
{
    if (enumType != null)
        if (enumType.IsEnum)
        {
            IDictionary<float, string> enumList = new Dictionary<float, string>();

            foreach (object enumValue in Enum.GetValues(enumType))
                enumList.Add(Convert.ToSingle(enumValue), Convert.ToString(enumValue));

            return enumList;
        }
        else
            throw new ArgumentException("The provided type is not an enumeration.");
    else
        throw new ArgumentNullException("enumType");
}
static public IDictionary<EnumUnderlyingType, string> GetEnumList<EnumUnderlyingType>(Type enumType)
{
    if (enumType != null)
        if (enumType.IsEnum && typeof(EnumUnderlyingType) == Enum.GetUnderlyingType(enumType))
        {
            IDictionary<EnumUnderlyingType, string> enumList = new Dictionary<EnumUnderlyingType, string>();

            foreach (object enumValue in Enum.GetValues(enumType))
                enumList.Add((EnumUnderlyingType)enumValue, enumValue.ToString());

            return enumList;
        }
        else
            throw new ArgumentException("The provided type is either not an enumeration or the underlying type is not the same with the provided generic parameter.");
    else
        throw new ArgumentNullException("enumType");
}
静态公共IDictionary GetEnumList(类型enumType)
{
if(枚举类型!=null)
if(enumType.IsEnum&&typeof(EnumUnderlyingType)==Enum.GetUnderlyingType(enumType))
{
IDictionary enumList=新字典();
foreach(枚举中的对象枚举值。GetValues(枚举类型))
添加((EnumUnderlineType)enumValue,enumValue.ToString());
返回枚举列表;
}
其他的
抛出新ArgumentException(“提供的类型不是枚举,或者基础类型与提供的泛型参数不同。”);
其他的
抛出新ArgumentNullException(“enumType”);
}

或者您可以将其中一个与lazyberezovsky的解决方案结合使用,以避免空检查。或者更好地使用隐式转换提供解决方案(假设您有一个基础类型为char的枚举,您可以安全地将char转换为int,这意味着如果该方法被要求返回一个int键字典,该字典是带有基础类型为char的所提供枚举的枚举值,那么该方法应该可以正常工作,因为在int上存储char没有问题).

使用带有描述的枚举,并通过泛型方法获取指令(EnumValue,EnumValueDescription)的更好方法是在某个时间。我需要在下拉列表中查看筛选器时使用它。 您可以将其用于代码中的任何枚举

例如:

public static class EnumExtensions
{
    public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            FieldInfo field = type.GetField(name);
            if (field != null)
            {
                var attr = Attribute.GetCustomAttribute(field, typeof (DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return value.ToString();
    }

    public static Dictionary<T, string> EnumToDictionary<T>()
    {
        var enumType = typeof(T);

        if (!enumType.IsEnum)
            throw new ArgumentException("T must be of type System.Enum");

        return Enum.GetValues(enumType)
                   .Cast<T>()
                   .ToDictionary(k => k, v => (v as Enum).GetDescription());
    }
}

得到了什么错误?很可能将对象强制转换为int会引发错误error@MarcinJuraszek完全同意你的观点!顺便说一句,很好,增加了检查:)如果(!(T是System.Enum)),为什么不干脆
?使用
Type.IsEnum
有什么好处吗?@MarcinJuraszek nice,我也希望有一些通用约束,比如
where T:!enum
,可能位于
.NET 8
?@MarcinJuraszek
T
是一个类型,但您应该有类型的实例才能将其与
is
运算符库一起使用!我可以修改它以得到我需要的。