通过WCF服务传递枚举 [英] Passing enums via WCF service
问题描述
我需要seprate我的WCF服务项目的项目定义枚举。我创建包含枚举和其他数据的对象。当我通过WCF服务给客户传递对象,我收到了未找到。
I need to define an Enum in a project seprate to my WCF service project. I am creating an object which contains the enum and other data. when i pass the object via the WCF service to the client i get a not found.
枚举:
public enum Color
{
Red = 1,
Blue,
Green,
}
要传递
对象:
Object to be Passed:
public class MyObject
{
public Color ColorEnum { get; set; }
public string Name{ get; set; }
}
只有当我给对象的默认值说ColourEnum =颜色。红做的服务工作。如果没有设置它打破。我知道这是一个解决方法,但即时寻找一个解决方案,更有意义,而不是设置的套利价值。我只是想知道为什么它打破提前
Only if i give the object a default value of say ColourEnum = Color.Red does the service work. if it not set it breaks. i know this is a workaround but im looking for a solution that makes more sense instead of setting an arb value. and i just want to understand why it breaks
感谢
推荐答案
问题是该属性的默认值 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 ofRed = 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.
这篇关于通过WCF服务传递枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!