DataContract surrogate for amplified value type

末鹿安然 提交于 2019-12-11 03:08:32

问题


I want to use a custom aplified type (think Nullable) in a DataContract class. I tried to write a IDataContractSurrogate but it fails at deserialization.

My amplified type looks like this:

public struct Amplified<TValue>
{
    public TValue Value { get; set; }
    //... some special code ...
}

And a DataContract may look like this:

[DataContract] public class MyDTO
{
     [DataMember] public Amplified<string> SpecialString { get; set; }
}

The above code works but produces unnecessary nesting with the Value property of amplified type. I want the DataContract to represent the Ampliefied just as a normal string on the wire.

Is this possible with the DataContract Serializers (JSON & Xml)? Why do i get a InvalidCastException when using IDataContractSurrogate to replace Amplified with string?


回答1:


You cannot use surrogates for primitive types (i.e., you'll be able to convert from Amplified<T> to T when T is a primitive, but not the other direction). For a possible alternative, take a look at the section "Fine grained control of serialization format for primitives" at http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/06/wcf-extensibility-serialization-callbacks.aspx.



来源:https://stackoverflow.com/questions/8072320/datacontract-surrogate-for-amplified-value-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!