在不使用 DataContractAttribute 的情况下在 NetDataContractSerializer 中强制排序

Force order in NetDataContractSerializer without using DataContractAttribute

我想强制 NetDataContractSerializer 按特定顺序写入 属性 值,因为序列化程序按字母顺序写入它们。

我知道我可以通过向这些属性添加 [DataMember(Order = X)] 属性来实现此目的,但这仅在我将 [DataContract] 属性添加到我正在序列化的 class 时才有效。

不幸的是,我无法将 [DataContract] 属性添加到此 class,因为它的基础 class 没有。

还有其他方法强制下单吗?

我想出了使用自己的 ISerializationSurrogate 的想法,我可以自己处理获取正在序列化的属性。

private class MySerializationSurrogate<T> : ISerializationSurrogate
{
    private IEnumerable<DataMemberAttribute> GetXmlAttribs(PropertyInfo p) => p.GetCustomAttributes(false).OfType<DataMemberAttribute>();

    public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context)
    {
        var myobj = (T)obj;
        foreach (var property in myobj.GetType().GetProperties().Where(p => GetXmlAttribs(p).Any()).OrderBy(p => GetXmlAttribs(p).First().Order))
        {
            info.AddValue(property.Name, property.GetValue(myobj));
        }
    }

    public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
    {
        var myobj = (T)obj;
        foreach (var property in myobj.GetType().GetProperties().Where(p => GetXmlAttribs(p).Any()).OrderBy(p => GetXmlAttribs(p).First().Order))
        {
            property.SetValue(myobj, info.GetValue(property.Name, property.PropertyType));
        }
        return null;
    }
}

然后我将序列化代理分配给序列化程序。

var formatter = new NetDataContractSerializer();
var surrogateSelector = new SurrogateSelector();
surrogateSelector.AddSurrogate(typeof(T), new StreamingContext(StreamingContextStates.All), new MySerializationSurrogate<T>());
formatter.SurrogateSelector = surrogateSelector;

一切都像地狱一样。

注意 T 是对象的类型 serialized/deserialized。