Serialization DataMember (name) override issue

大兔子大兔子 提交于 2019-12-01 15:16:22
David Hodge

I had this same issue. I was using VB.NET and I had to Shadow (or Overload) the property to get WCF to respect the DataMember property in my derived class. In C# you should be able to use the new operator.

public class DerivedClass
{
    [DataMember(Name = "first_method")]
    new public string FirstMethod { get; protected set; }
}

The trick is to specify EmitDefaultValue = false for the base class's virtual data member, and in its implementation in the derived class return default value so the data member is not serialized. In the derived class define another data member with the required name.

[DataContract(Name = "baseclass", Namespace = "")]
[KnownType(typeof(DerivedClass))]
public class BaseClass
{
    [DataMember(Name = "attributes", EmitDefaultValue = false)]
     public virtual SomeType Fields { get; set; }
}

[DataContract(Name = "derivedclass", Namespace = "")]
public class DerivedClass : BaseClass
{
    public override SomeType Fields
    {
        get { return null; }
    }

    [DataMember(Name = "fields")]
    public SomeType DerivedFields
    {
        get { return base.Fields; }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!