DataContractAttribute行为不一致

时间:2009-07-25 04:10:36

标签: c# .net wcf serialization datacontract

根据我的理解,WCF的数据合同模型是选择加入asmx web-services的旧选择退出方法。您必须使用DataContractAttributeDataMemberAttribute明确包含所需的所有字段和类型。然而,我的经历却有所不同。

看看下面的例子,


///CASE: 1
///Behaves as excpected BoolValue is included but String Value is emitted
[DataContract]
public class CompositeType
{
    [DataMember]
    public bool BoolValue { get; set; }

    public string StringValue { get; set; }
}

///CASE: 2
///All elements are included, as if everything was marked.
public class CompositeType
{
   public bool BoolValue { get; set; }

    public string StringValue { get; set; }
}

///CASE: 3
/// MyEnum Type is included even though the MyEnum is not marked.
[DataContract]
public class CompositeType
{
    [DataMember]
    public bool BoolValue { get; set; }

    [DataMember]
    public string StringValue { get; set; }

    [DataMember]
    public MyEnum EnumValue{ get; set; }
}

public enum MyEnum
{
    hello = 0,
    bye = 1
}

///CASE: 4
/// MyEnum Type is no longer included. EnumValue is serialized as a string
[DataContract]
public class CompositeType
{
    [DataMember]
    public bool BoolValue { get; set; }

    [DataMember]
    public string StringValue { get; set; }

    [DataMember]
    public MyEnum EnumValue{ get; set; }
}

[DataContract]
public enum MyEnum
{
    hello = 0,
    bye = 1
}

///CASE: 5
//Both hello and bye are serilized
public enum MyEnum
{
    [EnumMember]
    hello = 0,
    bye = 1
}

///CASE: 6
//only hello is serilized
[DataContract]    
public enum MyEnum
{
    [EnumMember]
    hello = 0,
    bye = 1
}

我只能说是WCF WTF?

2 个答案:

答案 0 :(得分:3)

根据定义,枚举始终可序列化。定义新的枚举时,不需要在其上应用DataContract属性,并且可以在数据协定中自由使用它。如果要从数据协定中排除某些枚举值,则需要先装饰枚举使用DataContract属性。然后,将EnumMemberAttribute明确应用于要包含在枚举数据协定中的所有枚举值。喜欢这个

[DataContract]
enum ContactType
{
   [EnumMember]
   Customer,

   [EnumMember]
   Vendor,

   //Will not be part of data contract
   Partner
}

将导致此线表示:

enum ContactType
{
   Customer,
   Vendor
}

对于类不正确,第一种情况的解释是什么,请参阅Programming WCF Services

答案 1 :(得分:0)

注意:我没有使用过WCF&这纯粹是基于阅读。

案例2:如果CompositeType用作服务的属性/字段/返回值,它将被序列化(因为它是公共的)。

案例3:与案例2相同。因为容器类型是可序列化的,所以enum(虽然没有标记)将被序列化。

案例4:枚举将被序列化为字符串。应用EnumMember时,可以使用Value属性来更改序列化值。

案例5:与案例2相同

案例6:你对Enum& amp;已经为其中一个枚举值应用了DataContract,DataMember。从而告诉序列化器忽略枚举的其他成员。

请不要批评,因为这纯粹是基于对文档阅读的快速浏览:)