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();
        }
    }
}
相关推荐
逝水无殇11 小时前
C# 异常处理详解
开发语言·后端·c#
玖玥拾12 小时前
C# 语言进阶(十五)C# 游戏服务端 MySQL 数据库
服务器·开发语言·网络·数据库·mysql·c#
逝水无殇13 小时前
C# 文件的输入与输出详解
开发语言·数据库·后端·c#
唐青枫18 小时前
看懂 IL 的关键:C#.NET 栈机执行模型实战拆解
c#·.net
我才是银古19 小时前
从零构建 Windows 桌面 RPA 框架:Go 与 .NET 的跨语言协奏
c#·go·rpa
逝水无殇21 小时前
C# 正则表达式详解
开发语言·后端·正则表达式·c#
朱永博21 小时前
使用Onnruntime实现Padim/Patchcore推理
开发语言·c#
吴可可1231 天前
C# CAD二次开发添加带按钮的窗口
c#
铅笔侠_小龙虾1 天前
Rust 学习(8)-切片类型
学习·rust·c#
习明然1 天前
我的本地化AI项目(三)
人工智能·python·electron·c#·avalonia