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();
        }
    }
}
相关推荐
YuanlongWang1 天前
C# 基础——装箱和拆箱
java·开发语言·c#
QQ12958455041 天前
C# 如何能够创建一个MVC的WEB项目
c#·mvc
星河队长1 天前
VS创建C++动态库和C#访问过程
java·c++·c#
William_cl1 天前
【C# MVC 前置】异步编程 async/await:从 “卡界面” 到 “秒响应” 的 Action 优化指南(附微软官方避坑清单)
microsoft·c#·mvc
yong99901 天前
C#驱动斑马打印机实现包装自动打印
java·数据库·c#
Jose_lz1 天前
C#开发学习杂笔(更新中)
开发语言·学习·c#
mingupup1 天前
WPF/C#:使用Microsoft Agent Framework框架创建一个带有审批功能的终端Agent
c#·wpf
YuanlongWang2 天前
C# 设计模式——单例模式
单例模式·设计模式·c#
YuanlongWang2 天前
C#基础——GC(垃圾回收)的工作流程与优化策略
java·jvm·c#
YuanlongWang2 天前
C# 基础——多态的实现方式
java·c#