如何有条件地避免在WCF中序列化属性? [英] How to conditionally avoid property from serializing in WCF?

查看:40
本文介绍了如何有条件地避免在WCF中序列化属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以动态避免序列化属性?假设我在WCF服务中遇到了这样的问题:

Is it possible to dynamically avoid property from serializing? Let's say I have got such a metod in my WCF Service:

public CompositeType GetDataUsingDataContract(CompositeType composite)
{
    return new CompositeType();
}

其中CompositeType看起来像这样:

Where CompositeType looks like this:

[DataContract]
public class CompositeType
{
    public bool _flag = true;

    [DataMember]
    public decimal? Value { get; set; }
}

当我调用GetDataUsingDataContract方法时,我将返回CompositeType对象,然后该对象将通过WCF技术序列化为XML.如果_flag = true,是否可以避免Value属性进行序列化?

When I invoke GetDataUsingDataContract methods, I'm returning CompositeType object, which is then serializing to XML by the WCF technology. Is it possible to avoid Value property from serializing if the _flag = true?

我读到有关[XmlIgnore],[IgnoreDataMember]等的信息,但是据我了解,它将始终忽略序列化的属性,只有在flag = true时,我才必须忽略它.如果flag = false,我仍然想序列化此属性.

I read about the [XmlIgnore], [IgnoreDataMember] etc., but what I understand this will always ignore property from serializing, I have to ignore only if flag = true. If flag = false I still want to serialize this property.

推荐答案

如果我了解您的要求,则应该可以使用以下方法.属性 ValueIfFlagTrue 仅用于序列化,请根据需要命名.您尚未说过要如何处理反序列化,所以我在实现过程中做了一个猜测:根据需要进行调整.

If I've understood your requirement, the following should work. The property ValueIfFlagTrue is for serialization only, name it as you wish. You haven't said how you want to handle deserializing, so I've made a guess in the implementation: adjust as needed.

[DataContract]
public class CompositeType
{
    public bool _flag = true;

    public decimal? Value { get; set; }

    [DataMember(Name = "Value", EmitDefaultValue = false)]
    private decimal? ValueIfFlagTrue
    {
        get
        {
            return _flag ? Value : null;
        }
        set
        {
            _flag = value.HasValue ? true : false;
            Value = value;
        }
    }
}

已更新

您可以将 DataMember 属性放在私有属性上,因此无需公开公开 ValueIfFlagTrue 属性.

You can put the DataMember attribute on a private property, so there's no need to expose the ValueIfFlagTrue property publicly.

这篇关于如何有条件地避免在WCF中序列化属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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