更新时间:2023-11-08 08:23:46
问题是该属性的默认值 ColorEnum
不是你的枚举的有效值:当你创建一个为MyObject
,该属性的默认值是0,0不符合您的枚举的任意值。
The problem is the default value for the property ColorEnum
is not a valid value for your enum: when your create a MyObject
, the default value for the property is 0, and 0 does not correspond to any value of your enum.
您有多种选择来纠正这种行为。
You have multiple options to correct this behavior.
红= 0
而不是红= 1
(甚至忽略它,它也有同样的效果)在枚举声明。这样的话,默认值将是红色的,而不是无意义的值。颜色?
,所以空将成为既是一个法律价值和默认为属性您可以为MyObject
的构造函数指定默认颜色的ColorEnum属性。
Red = 0
instead of Red = 1
(or even omit it, it would have the same effect) in your enum declaration. That way, the default value would be Red instead of a nonsensical value.Color?
, so null would become both a legal value and the default for the propertyYou can have the constructor of MyObject
assign a default color to the ColorEnum property.
公开为MyObject()
{
this.ColorEnum = Color.Red;
}
public MyObject() { this.ColorEnum = Color.Red; }
但是,不管你做什么,一个枚举类型的defaul值将始终为0,如果0不对应于合法枚举构件,它必然是一个问题。
But whatever you do, the defaul value for an enumeration type will always be 0. if 0 does not correspond to a legal enum member, it's bound to be a problem.