开发者

How to ignore the property of the base class in the derived class while using the XmlSerializer?

I have a class like this:

[Serializable]
    public class Structure
    {
        #region Constants and Fields

        /// <summary>
        /// The description.
        /// </summary>
        private string description;


        #endregion


        /// <summary>
        ///   Gets or sets the Description of the subclass i.e subtype of structure
        /// </summary>
        public string Description
        {
            get
            {
                return this.description;
            }

            set
            {
                this.description = value;
            }
        }
}

Another class like below inherits above one:

[XmlRoot(Namespace = "TestNamespace", ElementName = "OrgStructure")]
    public class OrgStructure : Structure
    {


        private long orgDeptID;

        /// <summary>
        ///   The description
        /// </sum开发者_StackOverflowmary>
        private string description;

  public long OrgDeptID
        {
            get
            {
                return this.orgDeptID;
            }

            set
            {
                this.orgDeptID= value;

            }
        }
}

I am migrating ASMX service to WCF keeping them compatible with existing ASMX clients. So I have to use the XmlSerializer instead of DataContractSerializer.

The OrgStructure is declared as MessageBodyMember in the response type of an OperationContract.

The ASMX client does NOT expect the Description in the XML message. So I tried to hide (using new operator) the Description property in the derived class and applied XmlIgnoreAttribute to it. But still it serializes this property.

(Please note that the declaration of the description variable. I do not know why developer declared again the derived class instead keeping it protected in the base class itself.)

How can I ignore the property of the base class in the derived class while using the XmlSerializer? I cannot ignore it in the base class since other subtypes of Structure need it.


To the base class, add:

public virtual bool ShouldSerializeDescription() { return true; }

and to the derived class, add:

public override bool ShouldSerializeDescription() { return false; }

This is a pattern that XmlSerializer recognises, but must be declared at the same level as the member (Description), hence the need to make it virtual.

If it offends the eye, add some:

[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]

to it - but it must be public to work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜