将枚举设置为其默认值
我确信这是相当微不足道的,但我无法做到正确。
public static string DoSomething(this Enum value)
{
if (!Enum.IsDefined(value.GetType(), value))
{
// not a valid value, assume default value
value = default(value.GetType());
}
// ... do some other stuff
}
value = default(value.GetType());
行无法编译,但希望您能看到我正在尝试的内容。我需要将枚举参数设置为其自身类型的默认值。
I'm sure this is fairly trivial but I can't get it right.
public static string DoSomething(this Enum value)
{
if (!Enum.IsDefined(value.GetType(), value))
{
// not a valid value, assume default value
value = default(value.GetType());
}
// ... do some other stuff
}
The line value = default(value.GetType());
doesn't compile, but hopefully you can see what I'm attempting. I need to set the Enum param to the default value of it's own type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不太确定你想在这里做什么,但是可以编译的“默认”行的版本是这样的:
或者,甚至更干净(来自 Paw,在评论中,谢谢):
第二个版本仅如果您知道枚举的第一个元素的值为零,则可以正常工作。
I'm not really sure what you're trying to do here, but a version of the 'default' line which does compile is this:
Or, even cleaner (from Paw, in the comments, thanks):
This second version does only work properly if you know the enum's first element has a value of zero.
你实际上可以做Paw建议的,甚至具有通用约束,如果您可以将此方法移动到它自己的类中:
那么您会这样做,例如:
正如 Konrad Rudolph 在评论中指出的那样,上面代码中的
default(TEnum)
将计算为 0,无论是否为给定 TEnum 类型定义了 0 值。如果这不是您想要的,Will 的答案提供当然是获取第一个定义值的最简单方法((TEnum)Enum.GetValues(typeof(TEnum)).GetValue(0)
)。另一方面,如果您想将其发挥到极致,并缓存结果,这样您就不必总是将其装箱,您可以这样做:
You actually could do what Paw is suggesting, even with a generic constraint, if you could move this method to its own class:
Then you would do, for example:
As Konrad Rudolph points out in a comment,
default(TEnum)
in the above code will evaluate to 0, regardless of whether or not a value is defined for 0 for the givenTEnum
type. If that's not what you want, Will's answer provides certainly the easiest way of getting the first defined value ((TEnum)Enum.GetValues(typeof(TEnum)).GetValue(0)
).On the other hand, if you want to take this to the extreme, and cache the result so that you don't always have to box it, you could do that:
Activator.CreateInstance(typeof(ConsoleColor))
似乎有效Activator.CreateInstance(typeof(ConsoleColor))
seems to workEnum
默认将其第一个值
作为默认值
Enum
by default have itsfirst value
asdefault value
您是否考虑过将其设为通用方法?
该方法的调用者应该知道该方法的类型。
Have you thought about making it a generic method?
The caller of the method should know the type.