为什么 C# 允许无效的枚举值
我花了一段时间试图理解为什么我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,不幸的是没有。
实际上,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.