江苏网站建设渠道,洮南网站建设哪家专业,合同模板网,网站建设的调查问卷写多了go代码#xff0c;被go mod tidy惯坏了#xff0c;还以为全天下的都很好用呢#xff0c;结果发现并不是这样。尤其是项目组的proto还是又封了个工具直接就能跑得#xff0c;导致以为没那么复杂的事情变得复杂了起来。是有两套生成的规则#xff0c;时间有点晚#…写多了go代码被go mod tidy惯坏了还以为全天下的都很好用呢结果发现并不是这样。尤其是项目组的proto还是又封了个工具直接就能跑得导致以为没那么复杂的事情变得复杂了起来。是有两套生成的规则时间有点晚没怎么仔细研究先记录一下。
先用nuget装protobuf-net、Google.Protobuf这两个软件包
protoc生成
不过我发现了C#和其他语言不太语言可以protoc生成C#代码然后使用的是Google.Protobuf这个包。 在Net Core6.0中是这么写的 这样生成 protoc --csharp_outproto test.proto
syntax proto3; // proto 版本
option go_package paramecium/proto/test; // 包名声明符
option csharp_namespace test;message SearchResultPage2 {string result 1;int32 num_results 2;
}using Google.Protobuf;Console.WriteLine(Hello, World!);
SearchResultPage2 s new SearchResultPage2();
s.Result 100;byte[] bytes s.ToByteArray();SearchResultPage2 deserializedPerson SearchResultPage2.Parser.ParseFrom(bytes);
Console.WriteLine(result:{0},deserializedPerson.Result);protogen生成
这个生成出来的代码不能用Google.Protobuf这个包要使用protobuf-net这个包才行并且代码也不太一样这个没有具体运行过来一份ChatGPT给的代码主要可以看下序列化和反序列化的接口
using System;
using System.IO;
using ProtoBuf;namespace Example
{class Program{static void Main(string[] args){// Create a new person objectPerson person new Person { id 1001, name Tom, age 26, isEmployed true };// Serialize person to a byte arraybyte[] buffer;using (MemoryStream stream new MemoryStream()){Serializer.Serialize(stream, person);buffer stream.ToArray();}// Deserialize byte array to a new person objectPerson newPerson;using (MemoryStream stream new MemoryStream(buffer)){newPerson Serializer.DeserializePerson(stream);}// Output the deserialized person objectConsole.WriteLine($Name: {newPerson.name});Console.WriteLine($Age: {newPerson.age});Console.WriteLine($Employed: {newPerson.isEmployed});Console.ReadLine();}}
}