首页 > 解决方案 > Derive/Override the DataMemberAttribute

问题描述

I'd like to override some of the functionality of the DataMemberAttribute but cannot create a derived class because it is marked as 'sealed'.

What I would like to do is have EmitDefaultValue be defaulted to 'false' instead of 'true' and I'd also like to not "emit" a collection if it is null or empty.

Any ideas?


Commenter wanted an example. There really isn't a way to show an example and I believe my question is fairly clear. But what the heck, here goes.

Instead of having to do this on every property:

[DataContract]
public class MyDto
{
  [DataMember( EmitDefaultValue = false )]
  public string Name { get; set; }

  [DataMember( EmitDefaultValue = false )]
  public string Occupation { get; set; }

  [DataMember( EmitDefaultValue = false )]
  public List<string> Friends { get; set; }
}

I'd like to be able to do this:

[DataContract]
public class MyDto
{
  [CustomSerialization]
  public string Name { get; set; }

  [CustomSerialization]
  public string Occupation { get; set; }

  [CustomSerialization]
  public List<string> Friends { get; set; }
}

And for the last property "Friends", if it is null or empty, to not serialize it in the output.

标签: c#serializationdata-bindingasp.net-core-mvcasp.net-core-1.0

解决方案


推荐阅读