C# C语言中的枚举到字典#
我已经在网上搜索过了,但是我找不到我想要的答案 基本上,我有以下枚举:C# C语言中的枚举到字典#,c#,dictionary,collections,enums,C#,Dictionary,Collections,Enums,我已经在网上搜索过了,但是我找不到我想要的答案 基本上,我有以下枚举: public enum typFoo : int { itemA : 1, itemB : 2 itemC : 3 } 如何将此枚举转换为字典,以便它存储在以下字典中 Dictionary<int,string> myDic = new Dictionary<int,string>(); 有什么想法吗?您可以通过枚举描述符枚举: Dictionary<int, string
public enum typFoo : int
{
itemA : 1,
itemB : 2
itemC : 3
}
如何将此枚举转换为字典,以便它存储在以下字典中
Dictionary<int,string> myDic = new Dictionary<int,string>();
有什么想法吗?您可以通过枚举描述符枚举:
Dictionary<int, string> enumDictionary = new Dictionary<int, string>();
foreach(var name in Enum.GetNames(typeof(typFoo))
{
enumDictionary.Add((int)((typFoo)Enum.Parse(typeof(typFoo)), name), name);
}
字典枚举字典=新字典();
foreach(Enum.GetNames中的变量名(typeof(typFoo))
{
enumDictionary.Add((int)((typFoo)Enum.Parse(typeof(typFoo)),name),name);
}
这应该将每个项目的值和名称放入词典。如果只需要名称,则根本不需要创建词典 这将把enum转换为int:
int pos = (int)typFoo.itemA;
这将把int转换为enum:
typFoo foo = (typFoo) 1;
这将重新运行它的名称:
((typFoo) i).toString();
尝试:
var dict=Enum.GetValues(typeof(fooEnumType))
.Cast()
.ToDictionary(t=>(int)t,t=>t.ToString());
使用反射:
Dictionary<int,string> mydic = new Dictionary<int,string>();
foreach (FieldInfo fi in typeof(typFoo).GetFields(BindingFlags.Public | BindingFlags.Static))
{
mydic.Add(fi.GetRawConstantValue(), fi.Name);
}
Dictionary mydic=newdictionary();
foreach(类型为(typFoo).GetFields(BindingFlags.Public | BindingFlags.Static)的FieldInfo-fi)
{
添加(fi.GetRawConstantValue(),fi.Name);
}
请参见:
进行调整,以便将其用作通用方法(谢谢,):
公共静态字典EnumDictionary()
{
if(!typeof(T).IsEnum)
抛出新ArgumentException(“类型必须是枚举”);
返回Enum.GetValues(typeof(T))
.Cast()
.ToDictionary(t=>(int)(object)t,t=>t.ToString());
}
+1到。这是VB.NET版本
以下是Ani答案的VB.NET版本:
Public Enum typFoo
itemA = 1
itemB = 2
itemC = 3
End Enum
Sub example()
Dim dict As Dictionary(Of Integer, String) = System.Enum.GetValues(GetType(typFoo)) _
.Cast(Of typFoo)() _
.ToDictionary(Function(t) Integer.Parse(t), Function(t) t.ToString())
For Each i As KeyValuePair(Of Integer, String) In dict
MsgBox(String.Format("Key: {0}, Value: {1}", i.Key, i.Value))
Next
End Sub
附加示例 在我的例子中,我想保存重要目录的路径并将它们存储在我的
web.config
文件的AppSettings部分。然后我创建了一个枚举来表示这些AppSettings的键……但是我的前端工程师需要访问外部JavaScript文件中的这些位置。因此,我创建了以下代码块并放置现在,每个新的枚举项将自动创建一个相应的JavaScript变量。下面是我的代码块:
<script type="text/javascript">
var rootDirectory = '<%= ResolveUrl("~/")%>';
// This next part will loop through the public enumeration of App_Directory and create a corresponding JavaScript variable that contains the directory URL from the web.config.
<% Dim App_Directories As Dictionary(Of String, App_Directory) = System.Enum.GetValues(GetType(App_Directory)) _
.Cast(Of App_Directory)() _
.ToDictionary(Of String)(Function(dir) dir.ToString)%>
<% For Each i As KeyValuePair(Of String, App_Directory) In App_Directories%>
<% Response.Write(String.Format("var {0} = '{1}';", i.Key, ResolveUrl(ConfigurationManager.AppSettings(i.Value))))%>
<% next i %>
</script>
var rootDirectory='';
//下一部分将循环遍历App_目录的公共枚举,并创建一个相应的JavaScript变量,该变量包含web.config中的目录URL。
注意:在本例中,我使用枚举的名称作为键(而不是int值)。使用:
public static class EnumHelper
{
public static IDictionary<int, string> ConvertToDictionary<T>() where T : struct
{
var dictionary = new Dictionary<int, string>();
var values = Enum.GetValues(typeof(T));
foreach (var value in values)
{
int key = (int) value;
dictionary.Add(key, value.ToString());
}
return dictionary;
}
}
公共静态类EnumHelper
{
公共静态IDictionary ConvertToDictionary(),其中T:struct
{
var dictionary=newdictionary();
var values=Enum.GetValues(typeof(T));
foreach(值中的var值)
{
int键=(int)值;
Add(key,value.ToString());
}
返回字典;
}
}
用法:
public enum typFoo : int
{
itemA = 1,
itemB = 2,
itemC = 3
}
var mydic = EnumHelper.ConvertToDictionary<typFoo>();
公共枚举类型foo:int
{
项目a=1,
项目b=2,
项目c=3
}
var mydic=EnumHelper.ConvertToDictionary();
- 扩展方法
- 常规命名
- 一行
- C#7返回语法(但您可以在旧版本的C#中使用括号)
- 如果类型不是
,由于System.Enum
Enum.GetValues
- IntelliSense将仅限于结构(还没有可用的
约束)enum
- 如果需要,允许您使用enum索引到字典中
publicstaticdictionary ToDictionary(),其中T:struct
=>Enum.GetValues(typeof(T)).Cast().ToDictionary(e=>e,e=>e.ToString());
另一种基于以下内容的扩展方法:
//
///返回父枚举的Dictionaryint字符串。请注意,扩展方法必须
///如果使用其中一个枚举值调用,则使用哪一个枚举值并不重要。
///示例调用:var myDictionary=StringComparison.Ordinal.ToDictionary()。
///
///枚举值(例如StringComparison.Ordianal)。
///字典的键=枚举数,值=关联文本。
公共静态字典ToDictionary(此枚举枚举值)
{
var enumType=enumValue.GetType();
返回Enum.GetValues(enumType)
.Cast()
.ToDictionary(t=>(int)(object)t,t=>t.ToString());
}
他没有问如何在int
和typFoo
之间转换。我知道Enum.ToString()
与此有关:)+1这实际上是问题的最直接答案。我见过使用方法扩展和反射的方法,但如果可以使用linq实现这一点,就不需要了。我正在尝试将其转换为VB.net,但我似乎在使用.Cast()
行时遇到了问题。我尝试了.Cast(typeFoo)
,但是得到了一个无效的Cast异常。修复了它!我正试图使用Enum.GetNames()
而不是Enum.GetValues()
。这正是我想要的。这可能是最复杂的方法;-)。啊哈是的。。。但直到现在,这是我唯一知道的方法D xD:p性能影响是什么?在序列化过程中使用反射是一个真正的性能杀手。为什么首先需要这样做?我忍不住想知道是否有更好的方法来解决你使用这本词典的任何问题。@juharr 26到目前为止,其他人发现它很有用-你看到了吗?我需要将其传递到UI层,以便基本上可以在javascript中使用枚举(在下拉列表中),而无需对值进行硬编码。这是处理多个枚举项具有相同值的情况的唯一答案。这可能是一种反模式,但这至少有助于识别案例,而不是返回重复的条目,如果有可能多个枚举条目具有相同的值,请使用Enum.GetValues
小心回答。这是可以理解的
Public Enum typFoo
itemA = 1
itemB = 2
itemC = 3
End Enum
Sub example()
Dim dict As Dictionary(Of Integer, String) = System.Enum.GetValues(GetType(typFoo)) _
.Cast(Of typFoo)() _
.ToDictionary(Function(t) Integer.Parse(t), Function(t) t.ToString())
For Each i As KeyValuePair(Of Integer, String) In dict
MsgBox(String.Format("Key: {0}, Value: {1}", i.Key, i.Value))
Next
End Sub
<script type="text/javascript">
var rootDirectory = '<%= ResolveUrl("~/")%>';
// This next part will loop through the public enumeration of App_Directory and create a corresponding JavaScript variable that contains the directory URL from the web.config.
<% Dim App_Directories As Dictionary(Of String, App_Directory) = System.Enum.GetValues(GetType(App_Directory)) _
.Cast(Of App_Directory)() _
.ToDictionary(Of String)(Function(dir) dir.ToString)%>
<% For Each i As KeyValuePair(Of String, App_Directory) In App_Directories%>
<% Response.Write(String.Format("var {0} = '{1}';", i.Key, ResolveUrl(ConfigurationManager.AppSettings(i.Value))))%>
<% next i %>
</script>
public static class EnumHelper
{
public static IDictionary<int, string> ConvertToDictionary<T>() where T : struct
{
var dictionary = new Dictionary<int, string>();
var values = Enum.GetValues(typeof(T));
foreach (var value in values)
{
int key = (int) value;
dictionary.Add(key, value.ToString());
}
return dictionary;
}
}
public enum typFoo : int
{
itemA = 1,
itemB = 2,
itemC = 3
}
var mydic = EnumHelper.ConvertToDictionary<typFoo>();
public static Dictionary<T, string> ToDictionary<T>() where T : struct
=> Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(e => e, e => e.ToString());
/// <summary>
/// Returns a Dictionary<int, string> of the parent enumeration. Note that the extension method must
/// be called with one of the enumeration values, it does not matter which one is used.
/// Sample call: var myDictionary = StringComparison.Ordinal.ToDictionary().
/// </summary>
/// <param name="enumValue">An enumeration value (e.g. StringComparison.Ordianal).</param>
/// <returns>Dictionary with Key = enumeration numbers and Value = associated text.</returns>
public static Dictionary<int, string> ToDictionary(this Enum enumValue)
{
var enumType = enumValue.GetType();
return Enum.GetValues(enumType)
.Cast<Enum>()
.ToDictionary(t => (int)(object)t, t => t.ToString());
}