我可以防止反序列化特定数据成员吗? [英] Can I prevent a specific datamember from being deserialized?

查看:133
本文介绍了我可以防止反序列化特定数据成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据合同

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

    [DataMember]
    public string DM2;

    [DataMember]
    public string DM3;
}

有时 我想防止DM2被从OperationContract返回时反序列化。像这样的事情:

and sometimes I want to prevent DM2 from being deserialized when being returned from an OperationContract. Something like this:

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

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

    return mdc;
}

我总是可以制作一个只有DM1和DM3的新DataContract并生成从MyDC实例,但我想看看是否有可能以编程方式删除DM2。可能吗?

I could always make a new DataContract that has only DM1 and DM3 and generate that from the MyDC instance but I want to see if it is possible to programatically remove DM2. Is it possible? How?

推荐答案

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

    public string DM2;

    public bool IsDM2Serializable;

    [DataMember(Name="DM2", EmitDefaultValue = false)]
    public string DM2SerializedConditionally
    {
        get
        {
            if(IsDM2Serializable)
                return null;
            return DM2;
        }
        set { DM2=value; }
    }

    [DataMember]
    public string DM3;
}

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

Then set IsDM2Serializable to false when you need to hide it:

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

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

    return mdc;
}

这篇关于我可以防止反序列化特定数据成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆