且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过WCF服务传递枚举

更新时间: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 (甚至忽略它,它也有同样的效果)在枚举声明。这样的话,默认值将是红色的,而不是无意义的值。

  • 您可以将默认值默认值= 0添加到您的枚举,你知道将有颜色的含义无法定义。

  • 您可以有你的属性格式是一个可空颜色?,所以空将成为既是一个法律价值和默认为属性

  • 您可以为MyObject 的构造函数指定默认颜色的ColorEnum属性。

  • You can have 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.
  • You can add a default value Default = 0 to your enum that you know will have the meaning of "the color has not be defined".
  • You can have your propery be a nullable Color?, so null would become both a legal value and the default for the property
  • You 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.