using System.IO; namespace ProtoCSStruct { /// /// 定义接口,方便代码使用 /// public interface IStructMessage { void ReadFrom(CodedInputStream input); void WriteTo(CodedOutputStream output); int CalculateSize(); void Clear(); string GetName(); string ToString(); } public interface IStructMessage : IStructMessage where T : struct, IStructMessage { } public interface IStructMessageParser { void ParseFrom(byte[] data); string GetMessageString(); string GetMessageName(); IStructMessageParser Clone(); } public class StructMessageParser : IStructMessageParser where T : struct, IStructMessage { /// /// 线程不安全,请逻辑层自己注意!!! /// T structData; CodedInputStream input; public void ParseFrom(byte[] data) { if(input != null) { input.Init(data); } else { input = new CodedInputStream(data); } structData.Clear(); structData.ReadFrom(input); return; } public string GetMessageString() { return structData.ToString(); } public string GetMessageName() { return structData.GetName(); } public ref T GetMessage() { return ref structData; } public ref T GetMessageClear() { structData.Clear(); return ref structData; } public IStructMessageParser Clone() { var cloneParser = new StructMessageParser(); cloneParser.structData = this.structData; return cloneParser; } } public static class StructMessageParseUtils { public static void ParseFrom(ref T message, byte[] buffer ) where T : struct, IStructMessage { CodedInputStream input = new CodedInputStream(buffer); message.ReadFrom(input); } public static byte[] ToByteArray(ref T message) where T : struct, IStructMessage { int size = message.CalculateSize(); byte[] buffer = new byte[size]; CodedOutputStream output = new CodedOutputStream(buffer); message.WriteTo(output); return buffer; } } }