问题描述
我想在DataContract类中使用自定义的aplified类型(认为是Nullable).我试图写一个IDataContractSurrogate
,但是在反序列化时失败.
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.
我的放大类型如下:
public struct Amplified<TValue>
{
public TValue Value { get; set; }
//... some special code ...
}
DataContract可能看起来像这样:
And a DataContract may look like this:
[DataContract] public class MyDTO
{
[DataMember] public Amplified<string> SpecialString { get; set; }
}
上面的代码可以工作,但是使用放大类型的Value属性会产生不必要的嵌套.我希望DataContract能够像导线上的普通字符串一样表示Ampliefied.
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.
使用DataContract序列化程序(JSON和Xml)可以做到吗?为什么使用IDataContractSurrogate将Amplified替换为string时会出现InvalidCastException?
Is this possible with the DataContract Serializers (JSON & Xml)?Why do i get a InvalidCastException when using IDataContractSurrogate to replace Amplified with string?
推荐答案
您不能对原始类型使用替代(即,当T是原始时,您可以将Amplified<T>
转换为T
)另一个方向).作为一种可能的替代方法,请参见 https://docs.microsoft.com/zh-CN/archive/blogs/carlosfigueira/wcf-extensibility-serialization-callbacks .
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 https://docs.microsoft.com/en-us/archive/blogs/carlosfigueira/wcf-extensibility-serialization-callbacks.
这篇关于用于放大值类型的DataContract代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!