Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.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 - Fatal编程技术网

C# 枚举到字典

C# 枚举到字典,c#,.net,C#,.net,我想实现一个扩展方法,将枚举转换为字典: public static Dictionary<int, string> ToDictionary(this Enum @enum) { Type type1 = @enum.GetType(); return Enum.GetValues(type1).Cast<type1>() //.OfType<typeof(@enum)>() .ToDictionary(e =

我想实现一个扩展方法,将枚举转换为字典:

public static Dictionary<int, string> ToDictionary(this Enum @enum)
{
    Type type1 = @enum.GetType();
    return Enum.GetValues(type1).Cast<type1>()
        //.OfType<typeof(@enum)>()
        .ToDictionary(e => Enum.GetName(@enum.GetType(), e));
}
公共静态字典目录(此Enum@Enum)
{
类型type1=@enum.GetType();
返回Enum.GetValues(type1.Cast())
//第()类
.ToDictionary(e=>Enum.GetName(@Enum.GetType(),e));
}
为什么它不编译

错误:

“类型或命名空间名称“type1” 找不到(您是否缺少 使用指令或程序集 参考?“


不能将type1用作泛型参数,因为它是变量,而不是类型

下面的代码执行与您的代码所显示的类似的操作:

public static Dictionary<string, TEnum> ToDictionary<TEnum>()
    where TEnum : struct
{
    if (!typeof(TEnum).IsEnum)
        throw new ArgumentException("Type must be an enumeration");
    return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().
            ToDictionary(e => Enum.GetName(typeof(TEnum), e));
}
公共静态字典ToDictionary()
其中TEnum:struct
{
if(!typeof(TEnum).IsEnum)
抛出新ArgumentException(“类型必须是枚举”);
返回Enum.GetValues(typeof(TEnum)).Cast()。
ToDictionary(e=>Enum.GetName(typeof(TEnum),e));
}
像这样使用它:

ToDictionary<Colors>()
ToDictionary()
但我不太确定,这是你所期望的吗


此外,它还有一个问题:您可以传递任何结构,而不仅仅是枚举,这将导致运行时异常。有关这方面的更多详细信息,请参阅。

好吧,您正在尝试使用类型为
type
的变量作为泛型类型参数。泛型是关于编译时类型的,不能这样做

您可以使用反射来实现,但最好将其作为通用方法。不幸的是,您不能将泛型类型参数约束为枚举,尽管我有一些技巧可以解决这个问题

如果做不到这一点,您可以对泛型方法使用
struct
类型约束,这将是一个良好的开端

现在,下一个问题是您试图获取
字典
——但是枚举的值不是
int
值。它们可能可以转换为
int
值,但它们不会立即出现。您可以使用
Convert.ToInt32
来执行此操作,但您必须做一些事情


最后(就目前而言),使用
uint
long
基础类型的枚举会发生什么情况?

下面是我用来转换枚举的扩展方法。唯一的区别是我返回IEnumerbale是为了我的目的:

public static IEnumerable<KeyValuePair<int, string>> ToListOfKeyValuePairs<TEnum>(this TEnum enumeration) where TEnum : struct
{
    return from TEnum e in Enum.GetValues(typeof(TEnum))
            select new KeyValuePair<int, string>
                (
                    (int)Enum.Parse(typeof(TEnum), e.ToString()),
                    Regex.Replace(e.ToString(), "[A-Z]", x => string.Concat(" ", x.Value[0])).Trim()
                );
}
用法:

<select>
<% foreach(var item in Province.BritishColumbia.ToListOfKeyValuePairs()){ %>
    <option value="<%=item.Key %>"><%=item.Value %></option>
<% } %>
</select>

输出:

<select>
    <option value="0">British Columbia</option>
    <option value="1">Ontario</option>
</select>

不列颠哥伦比亚省
安大略
尽管@Paul Ruane是正确的,但我发现这是一种非常有用的扩展方法。这不是一个完美的世界

但在这里,您的代码正在运行:

public static Dictionary<int, string> ToDictionary(this Enum @enum)
{
  var type = @enum.GetType();
  return Enum.GetValues(type).Cast<int>().ToDictionary(e => e, e => Enum.GetName(type, e));
}
公共静态字典目录(此Enum@Enum)
{
var type=@enum.GetType();
返回Enum.GetValues(type.Cast().ToDictionary(e=>e,e=>Enum.GetName(type,e));
}
基于:

public static SelectList to SelectList(此HtmlHelper h),其中TEnum:struct
{
返回新的选择列表(FortunaExtension.ToDictionary(),“Key”,“Value”);
}

为什么不向我们显示错误消息?这不是我所期望的。我想使用扩展方法。显示使用情况和预期输出的代码示例。(因为将其作为扩展方法调用似乎没有意义)@Alex Maslakov:扩展方法在这里并不真正合适,因为您要从静态可用的枚举数据(即,它是枚举类型定义中的数据,而不是使用特定枚举值的属性)构建字典。扩展方法对类型的实例进行操作。您可以通过编写
Cast
而不是
Cast
来稍微简化它,因为这样您可以在第一个lambda表达式中省略从object到int的转换。这不适用于所有枚举基础类型。还要检查
typeof(int)=Enum.GetUnderlyingType(type)
。如果您使用的是
Enum
的小写类型,请使用
typeof(@Enum)
而不是
@Enum.GetType()
。能否显示一个使用示例?public enum SomeEnum{A,B,C}和用法:var d=SomeEnum.A.ToDictionary();
public static Dictionary<int, string> ToDictionary(this Enum @enum)
{
  var type = @enum.GetType();
  return Enum.GetValues(type).Cast<int>().ToDictionary(e => e, e => Enum.GetName(type, e));
}
public static SelectList ToSelectList<TEnum>(this HtmlHelper h) where TEnum : struct
{
    return new SelectList(FortunaExtension.ToDictionary<TEnum>(), "Key", "Value");
}