How to serialize / deserialize immutable list type in c#

前端 未结 3 793
挽巷
挽巷 2020-12-10 16:28

If I have a class defined

[DataContract()]
class MyObject {
    [DataMember()]
    ImmutableList Strings { get; private set}
}
<
3条回答
  •  心在旅途
    2020-12-10 17:06

    One way to do this is to use a proxy mutable list and use the OnSerializing and OnDeserialized hooks

    [DataContract()]
    class MyObject {
    
        public ImmutableList Strings { get; private set}
    
        [DataMember(Name="Strings")]
        private List _Strings;
    
        [OnSerializing()]
        public void OnSerializing(StreamingContext ctxt){
            _Strings = Strings.ToList();
        }
    
        [OnDeserialized()]
        public void OnDeserialized(StreamingContext ctxt){
            Strings = ImmutableList.Empty.AddRange(_Strings);
        }
    }
    

    It's not super pretty but as Marc Gravell noted in his answer, DataContract serializer is broken with respects to immutable collections and there are no simple hooks to teach it how to behave without the above type of hack.

    UPDATE

    DataContract serializer is not broken. There is a way to hook surrogates in. See this separate answer showing an alternate technique.

    https://stackoverflow.com/a/18957739/158285

提交回复
热议问题