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();
        }
    }
}
相关推荐
friklogff13 分钟前
【C#生态园】从图像到视觉:Emgu.CV、AForge.NET、OpenCvSharp 全面解析
开发语言·c#·.net
friklogff2 小时前
【C#生态园】构建你的C#操作系统:框架选择与实践
服务器·开发语言·c#
code bean5 小时前
【C#基础】函数传参大总结
服务器·开发语言·c#
shanshan20996 小时前
上位机系统架构 | 如何设计一个高效的多相机管理系统
c#·wpf·相机
ling1s7 小时前
C#基础(13)结构体
前端·c#
.Net Core 爱好者8 小时前
Redis实践之缓存:设置缓存过期策略
java·redis·缓存·c#·.net
云草桑8 小时前
逆向工程 反编译 C# net core
前端·c#·反编译·逆向工程
指尖流烟10 小时前
C#调用图表的使用方法
开发语言·c#
friklogff12 小时前
【无标题】云端之C#:全面解析6种云服务提供商的SDK
开发语言·flask·c#
c#上位机13 小时前
C#事件的用法
java·javascript·c#