为什么 C# 允许无效的枚举值

发布于 2024-09-24 00:15:15 字数 381 浏览 0 评论 0原文

我花了一段时间试图理解为什么我的 WPF 应用程序没有正确地将数据绑定到枚举属性,这就是原因。

 static void Main(string[] args)
 {
  MyEnum x = 0;
  Console.WriteLine(x.ToString());
  Console.ReadLine();
 }

 public enum MyEnum
 {
  First = 1,
  Second = 2
 }

本质上,问题在于我绑定的类的构造函数中没有为枚举属性设置默认值,因此它默认为零。

我是否可以通过某种方式告诉 C# 编译器我希望它只接受有效值(并且默认为最低值)?我不希望我的属性接受无效值,并且我不想为每个使用枚举的属性编写设置器代码。

I've spent a while trying to understand why my WPF app wasn't databinding to an enum property propertly and this is the cause.

 static void Main(string[] args)
 {
  MyEnum x = 0;
  Console.WriteLine(x.ToString());
  Console.ReadLine();
 }

 public enum MyEnum
 {
  First = 1,
  Second = 2
 }

Essentially the problem was that there was no default value set for the enum property in the constructor of the class I was binding to, so it was defaulting to zero.

Is there someway I can tell the C# compiler that I want it to only accept valid values (and default to the lowest value)? I don't want my property to accept invalid values, and I don't want to have to write setter code for every property that uses an enum.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白昼 2024-10-01 00:15:15

不,不幸的是没有。

实际上,C# 枚举只是命名的数字 - 根本没有验证。我同意看到这一点以及具有行为的枚举(如 Java 中的枚举)会非常高兴。不过,我还没有听到任何消息表明它很快就会到来:(

请注意,类型的默认值始终是由“全零位”表示的值 - 在类型系统中确实没有办法解决这个问题 您需要将其设为合理的默认值,要么即使在验证系统中也必须对其进行显式测试(例如针对引用类型进行 null 测试)。

因此,要么 拥有“数字名称”类型是有意义的......但我认为一组真正受限制的值会更有用。

No, unfortunately not.

C# enums are just named numbers, really - there's no validation at all. I agree it would be very nice to see this, as well as enums with behaviour (like in Java). I haven't heard anything to suggest it's coming any time soon though :(

Note that the default value of a type will always be the value represented by "all zero bits" - there's no way of getting round that within the type system, really. So either you need to make that a sensible default value, or you'd have to explicitly test against it even in a validating system (like testing against null for reference types).

Just to be clear, I believe there are times when it makes sense to have the "names for numbers" kind of type... but I think a genuinely restricted set of values would be even more useful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文