C#使用proto

写多了go代码,被go mod tidy惯坏了,还以为全天下的都很好用呢,结果发现并不是这样。尤其是项目组的proto还是又封了个工具直接就能跑得,导致以为没那么复杂的事情变得复杂了起来。是有两套生成的规则,时间有点晚,没怎么仔细研究,先记录一下。

先用nuget装protobuf-net、Google.Protobuf,这两个软件包

protoc生成

不过我发现了,C#和其他语言不太语言,可以protoc生成C#代码,然后使用的是Google.Protobuf这个包。

在Net Core6.0中是这么写的

这样生成 protoc --csharp_out=proto test.proto

proto 复制代码
syntax = "proto3";                // proto 版本
option go_package = "paramecium/proto/test"; // 包名声明符
option csharp_namespace = "test";

message SearchResultPage2 {
  string result = 1;
  int32 num_results = 2;
}
csharp 复制代码
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给的代码,主要可以看下序列化和反序列化的接口

csharp 复制代码
using System;
using System.IO;
using ProtoBuf;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new person object
            Person person = new Person { 
                id = 1001, 
                name = "Tom", 
                age = 26, 
                isEmployed = true 
            };

            // Serialize person to a byte array
            byte[] buffer;
            using (MemoryStream stream = new MemoryStream())
            {
                Serializer.Serialize(stream, person);
                buffer = stream.ToArray();
            }

            // Deserialize byte array to a new person object
            Person newPerson;
            using (MemoryStream stream = new MemoryStream(buffer))
            {
                newPerson = Serializer.Deserialize<Person>(stream);
            }

            // Output the deserialized person object
            Console.WriteLine($"Name: {newPerson.name}");
            Console.WriteLine($"Age: {newPerson.age}");
            Console.WriteLine($"Employed: {newPerson.isEmployed}");
            Console.ReadLine();
        }
    }
}
相关推荐
唐青枫18 小时前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech1 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf3 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6253 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech3 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
2601_962072554 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
m0_547486664 天前
《C#语言程序设计与实践》 全套PPT课件
c语言·c#·c语言程序设计
叶帆4 天前
【YFIOs】用C#开发硬件之设备上云
开发语言·unity·c#
IT方大同4 天前
(嵌入式操作系统)信号量
嵌入式硬件·c#
z落落4 天前
C# FileStream文件流读取文件
开发语言·c#