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();
        }
    }
}
相关推荐
不绝1916 分钟前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
大鹏说大话22 分钟前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#
czhc11400756632 小时前
通信 28
c#
bugcome_com5 小时前
C# 程序结构详解:从 Hello World 开始
c#
唐梓航-求职中6 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
bugcome_com8 小时前
阿里云 OSS C# SDK 使用实践与参数详解
阿里云·c#
懒人咖18 小时前
缺料分析时携带用料清单的二开字段
c#·金蝶云星空
bugcome_com19 小时前
深入了解 C# 编程环境及其开发工具
c#
wfserial21 小时前
c#使用微软自带speech选择男声仍然是女声的一种原因
microsoft·c#·speech
阔皮大师1 天前
INote轻量文本编辑器
java·javascript·python·c#