c# – 有没有办法在protobuf-net代理类中定义替代转换函数(从/到
发布时间:2020-12-15 05:40:11 所属栏目:百科 来源:网络整理
导读:使用protobuf-net v2 build 668,我正在尝试序列化/反序列化一个类,该类包含一个定义为接口的成员,同时进行即时转换. 通常,代理方法可以正常工作,但由于C#不允许用户定义的接口转换,我无法定义转换. 谢谢, namespace ProtoBufNetTest{ using System.Diagnosti
使用protobuf-net v2 build 668,我正在尝试序列化/反序列化一个类,该类包含一个定义为接口的成员,同时进行即时转换.
通常,代理方法可以正常工作,但由于C#不允许用户定义的接口转换,我无法定义转换. 谢谢, namespace ProtoBufNetTest { using System.Diagnostics; using System.IO; using ProtoBuf; using ProtoBuf.Meta; class Program { static void Main() { RuntimeTypeModel.Default.Add(typeof(IDummy),false) .SetSurrogate(typeof(DummySurrogate)); var container = new Container { Data = new Dummy { Positive = 3 } }; using (var file = File.Create("test.bin")) { Serializer.Serialize(file,container); } using (var file = File.OpenRead("test.bin")) { container = Serializer.Deserialize<Container>(file); Debug.Assert(container.Data.Positive == 3); } } } // Outside of the project,cannot be changed public interface IDummy { int Positive { get; set; } } [ProtoContract] public class Container { [ProtoMember(1)] public IDummy Data { get; set; } } public class Dummy : IDummy { public int Positive { get; set; } } [ProtoContract] class DummySurrogate { [ProtoMember(1)] public int Negative { get; set; } // Does not compile : user-defined conversions to or from an interface are not allowed public static explicit operator IDummy(DummySurrogate value) { return value == null ? null : new Dummy { Positive = -value.Negative }; } // Does not compile : user-defined conversions to or from an interface are not allowed public static explicit operator DummySurrogate(IDummy value) { return value == null ? null : new DummySurrogate { Negative = -value.Positive }; } // Fake attribute,does not exist but could work if it did [ProtoConvertFrom] public static IDummy From(DummySurrogate value) { return value == null ? null : new Dummy { Positive = -value.Negative }; } // Fake attribute,does not exist but could work if it did [ProtoConvertTo] public static DummySurrogate To(IDummy value) { return value == null ? null : new DummySurrogate { Negative = -value.Positive }; } } } 解决方法
在当前版本中:不,没有.
但是,在下一个版本中,这很好用: [ProtoContract] class DummySurrogate { [ProtoMember(1)] public int Negative { get; set; } [ProtoConverter] public static IDummy From(DummySurrogate value) { return value == null ? null : new Dummy { Positive = -value.Negative }; } [ProtoConverter] public static DummySurrogate To(IDummy value) { return value == null ? null : new DummySurrogate { Negative = -value.Positive }; } } 基本上,标记为[ProtoConverter]的静态方法优先于定义的隐式或显式转换运算符,进一步的优点是[ProtoConverter]方法不受与运算符相同的语法规则的约束.没有必要定义单独的* To / * From属性,因为签名中的意图是明确的. 作为旁注:Dummy上的属性是不必要的,永远不会使用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |