Wcf 我可以防止反序列化特定的datamember吗?

Wcf 我可以防止反序列化特定的datamember吗?,wcf,serialization,datacontract,datamember,Wcf,Serialization,Datacontract,Datamember,我有一份这样的合同 [DataContract] class MyDC { [DataMember] public string DM1; [DataMember] public string DM2; [DataMember] public string DM3; } 有时我想防止DM2从OperationContract返回时被反序列化。大概是这样的: [OperationContact] public MyDC GetMyDC() {

我有一份这样的合同

[DataContract]
class MyDC 
{
    [DataMember]
    public string DM1;

    [DataMember]
    public string DM2;

    [DataMember]
    public string DM3;
}
有时我想防止DM2从OperationContract返回时被反序列化。大概是这样的:

[OperationContact]
public MyDC GetMyDC()
{
    MyDC mdc = new MyDC();

    if (condition)
    {
        // Code to prevent DM2 from being deserialized  
    }

    return mdc;
}

我总是可以创建一个只有DM1和DM3的新DataContract,并从MyDC实例生成它,但我想看看是否可以通过编程删除DM2。可能吗?如何实现?

您的意思是序列化而不是反序列化

如果将
[DataContract]
属性应用于类,则只有具有
[DataMember]
属性的类的成员才会被序列化:

[DataContract]
class MyDC 
{
    [DataMember]
    public string DM1;

    public string DM2;

    [DataMember]
    public string DM3;
}
在一些更复杂的情况下,使用
[IgnoreDataMember]
可以解决您的问题。(见附件)


顺便说一下,您可以序列化字段和属性,而不考虑可访问性:
private
protected
internal
protected internal
public
。您可以序列化任何读/写属性,而不仅仅是字段。关于集合类型的序列化,请参见。

执行此操作的一种方法是将DataMemberAttribute的EmitDefaultValue属性设置为false:

[DataContract]
class MyDC 
{
    [DataMember]
    public string DM1;

    [DataMember(EmitDefaultValue = false)]
    public string DM2;

    [DataMember]
    public string DM3;
}
然后将此属性设置为null:

[OperationContact]
public MyDC GetMyDC()
{
    MyDC mdc = new MyDC();

    if (condition)
    {
        // Code to prevent DM2 from being deserialized  
        mdc.DM2 = null;
    }

    return mdc;
}
这样,该属性就不会在序列化时写入输出流

然后在需要隐藏IsDM2Serializable时将其设置为false:

[OperationContact]
public MyDC GetMyDC()
{
    MyDC mdc = new MyDC();

    if (condition)
    {
        // Code to prevent DM2 from being serialized  
        mdc.IsDM2Serializable = false;
    }

    return mdc;
}

是的,我们可以阻止属性序列化。 将
[DataContract]
注释放在类上,并将
[DataMember]
仅用于序列化属性。如果要在该属性值为null时跳过该属性,请在该属性上放置
[DataMember(EmitDefaultValue=false)]

例如:

[DataContract]
public class MyClass 
{
    [DataMember]
    public int Id{ get; set; } 
    [DataMember]
    public string Title { get; set; }
    [DataMember]
    public string MessageBody { get; set; }

    [DataMember(EmitDefaultValue = false)]
    public DateTime SentOn { get; set; } 
}

注意:SentOn在不为null时将被序列化,其他的将在任何情况下被序列化。

如果我正在创建我想要序列化的实际对象的副本,并且不关心更改副本,那么这一点就行了。但是,我希望在不更改试图序列化的对象的情况下执行此操作。
[DataContract]
public class MyClass 
{
    [DataMember]
    public int Id{ get; set; } 
    [DataMember]
    public string Title { get; set; }
    [DataMember]
    public string MessageBody { get; set; }

    [DataMember(EmitDefaultValue = false)]
    public DateTime SentOn { get; set; } 
}