从枚举中获取值
我有一些代码设置了一个字典,其中包含枚举的一些默认值:
foreach (string status in Enum.GetNames(typeof(TargetStatusType)))
{
dict.Add((TargetStatusType)Enum.Parse(typeof(TargetStatusType), status), 0);
}
是否有更简单的方法来做到这一点,因为它看起来有点混乱。
我希望我能做
foreach(TargetStatusType status in ?) ...
谢谢!
I have some code that sets up a dictionary with some defualt values for an enum:
foreach (string status in Enum.GetNames(typeof(TargetStatusType)))
{
dict.Add((TargetStatusType)Enum.Parse(typeof(TargetStatusType), status), 0);
}
Is there an easier way to do this, as it seems a bit messy.
I was hoping I could just do
foreach(TargetStatusType status in ?) ...
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,这里不需要使用字典(或为此创建任何类型的新集合)。 此外,当您只需调用
GetValues
时,获取枚举值的名称然后解析它们是一个非常复杂的方法。以下内容应该可以完成这项工作:
对
Cast
扩展方法的调用意味着您的status
变量是强类型的(类型为TargetStatusType
),而不是而不是简单的object
类型。Firstly, there's no need to use a dictionary here (or to create any sort of new collection for that matter). Also, getting the names of the enum values and then parsing them is a awfully convoluted method when you can just call
GetValues
.The following should do the job:
The call to the
Cast
extension method means that yourstatus
variable is strongly-typed (of typeTargetStatusType
) rather than simply of typeobject
.如果这是字典的初始化(没有添加先前的值),您也可以使用 linq
dict = Enum.GetValues(typeof(TargetStatusType)).ToDictinary(en => en,x => 0)
但我不禁想知道为什么你要将它们添加到字典中。 你可能有很好的理由:)我想知道因为价值是相同的。 如果用于查找,则具有枚举的 int 值的数组索引将比字典快得多。 如果您不关心该值并且只想强制添加一次密钥,您可以使用 Hashset<> 反而
if this is the initialization of the dictionary (no prior values added) you could also use linq
dict = Enum.GetValues(typeof(TargetStatusType)).ToDictinary(en => en,x => 0)
but I can't help wonder why you would add them to a dictionary. you might have very good reasons :) Im wondering because the value is the same. If it's for a lookup an array index with the int value of the enum will be a lot faster than the dictionary. if you don't care bout the value and only wanna enforce adding the key once, you could use a Hashset<> instead
使用
Enum.GetValues()
< /a>:请注意,虽然
GetValues()
仅声明为返回Array
,但foreach
循环会自动为您执行转换。 或者,如果您想在不同的循环中使用结果,而转换每个值会很不方便,则可以将结果转换为TargetStatusType[]
。Use
Enum.GetValues()
:Note that although
GetValues()
is only declared to returnArray
, theforeach
loop performs the cast for you automatically. Alternatively you could cast the result toTargetStatusType[]
if you wanted to use it in a different loop where casting each value would be inconvenient.