WCF枚举问题:不能“或”枚举值

时间:2013-01-23 07:48:49

标签: wcf enums

我使用枚举作为标志,并希望"或"它,但始终遇到错误:

枚举值' 3'类型为' Common.EventType'并且无法序列化。确保存在必要的枚举值,并且如果类型具有DataContractAttribute属性,则使用EnumMemberAttribute属性标记

代码:

[DataContract]
public enum EventType
{
    [EnumMember]
    Event1 = 1,
    [EnumMember]
    Event2 = 2,
    [EnumMember]
    Event3 = 4,
    [EnumMember]
    AllEvents = Event1 | Event2 | Event3
}

MyContractClient proxy = new MyContractClient(context);

proxy.Subscribe( EventType.Event1 | EventType.Event2 );

提前谢谢

2 个答案:

答案 0 :(得分:3)

您需要添加[Flags]属性以通过WCF发送标志。

Enumeration Types in Data Contracts

[DataContract][Flags]
public enum EventType
{
  [EnumMember]
  Event1 = 1,
  [EnumMember]
  Event2 = 2,
  [EnumMember]
  Event3 = 4,
  [EnumMember]
  AllEvents = Event1 | Event2 | Event3
}

答案 1 :(得分:2)

当我遇到这个问题时:

... and cannot be serialized. Ensure that the necessary enum values are present 
and are marked with EnumMemberAttribute attribute if the type has 
DataContractAttribute attribute

我发现我不小心通过WCF代理将Enum作为 int 而不是实际的枚举值发送。

就我而言

bad: request.MyEnum = 1
good: request.MyEnum = MyActualEnum.Number1