最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Google.Protobuf工具在C#中的使用方法

 更新時間:2021年11月24日 16:01:31   作者:chenzk  
本文詳細講解了Google.Protobuf工具在C#中的使用方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

protobuf是一個語言無關、平臺無關的序列化協(xié)議,由谷歌開源提供。再加上其高性能、存儲占用更小等特點,在云原生的應用中越來越廣泛。

在C#中主要有兩種方法來使用protobuf協(xié)議,nuget包分別為Google.Protobufprotobuf-net,其中Google.Protobuf由谷歌官方提供。本文簡要記錄和展示Google.Protobuf的使用方法和特點。

項目資料及文檔

  • 項目官網:https://developers.google.cn/protocol-buffers?hl=zh-cn
  • github主頁:https://github.com/protocolbuffers/protobuf/
  • 官方文檔:https://developers.google.cn/protocol-buffers/docs/overview?hl=zh-cn
  • 該nuget包支持.NETFramework 4.5、.NETStandard1.1、.net5等

準備工作

需要用到的nuget有如下兩個:Google.Protobuf、Google.Protobuf.Tools,其中Google.Protobuf是主類庫,運行時要用到。Google.Protobuf.Tools提供了命令行工具,用于根據.proto文件轉為目標語言的類型,僅開發(fā)時使用,運行時不需要。

本次Demo使用的.proto文件內容如下:

syntax = "proto3";
option cc_enable_arenas = true;

package Tccc.Demo.Protobuf;

message ErrorLog {
    string LogID = 1;
    string Context = 2;
    string Stack = 3;
}

首先需要根據.proto文件生成目標類型,操作如下:

./google.protobuf.tools\3.19.1\tools\windows_x64\protoc.exe --csharp_out=./generatedCode ./proto/ErrorLog.proto

其中--csharp_out選項是生成C#語言的目標類型,運行protoc.exe -h 查看幫助信息,可以看到還支持一下幾種選項:

--proto_path=PATH
--cpp_out=OUT_DIR Generate C++ header and source.
--csharp_out=OUT_DIR Generate C# source file.
--java_out=OUT_DIR Generate Java source file.
--js_out=OUT_DIR Generate JavaScript source.
--kotlin_out=OUT_DIR Generate Kotlin file.
--objc_out=OUT_DIR Generate Objective-C header and source.
--php_out=OUT_DIR Generate PHP source file.
--python_out=OUT_DIR Generate Python source file.
--ruby_out=OUT_DIR Generate Ruby source file.

運行上述命令,會根據指定的ErrorLog.proto文件生成ErrorLog.cs文件,文件中就是C#類型ErrorLog。生成的代碼中會給此類型增加方法void WriteTo(CodedOutputStream output)和只讀屬性Parser,接下來進行序列化和反序列化的關鍵。

生成的ErrorLog類的完整代碼:

// <auto-generated>
//     Generated by the protocol buffer compiler.  DO NOT EDIT!
//     source: ProtoFiles/ErrorLog.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code

using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Tccc.Demo.Protobuf {

  /// <summary>Holder for reflection information generated from ProtoFiles/ErrorLog.proto</summary>
  public static partial class ErrorLogReflection {

    #region Descriptor
    /// <summary>File descriptor for ProtoFiles/ErrorLog.proto</summary>
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static ErrorLogReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "ChlQcm90b0ZpbGVzL0Vycm9yTG9nLnByb3RvEhJUY2NjLkRlbW8uUHJvdG9i",
            "dWYiOQoIRXJyb3JMb2cSDQoFTG9nSUQYASABKAkSDwoHQ29udGV4dBgCIAEo",
            "CRINCgVTdGFjaxgDIAEoCUID+AEBYgZwcm90bzM="));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { },
          new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
            new pbr::GeneratedClrTypeInfo(typeof(global::Tccc.Demo.Protobuf.ErrorLog), global::Tccc.Demo.Protobuf.ErrorLog.Parser, new[]{ "LogID", "Context", "Stack" }, null, null, null, null)
          }));
    }
    #endregion

  }
  #region Messages
  public sealed partial class ErrorLog : pb::IMessage<ErrorLog>
  #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      , pb::IBufferMessage
  #endif
  {
    private static readonly pb::MessageParser<ErrorLog> _parser = new pb::MessageParser<ErrorLog>(() => new ErrorLog());
    private pb::UnknownFieldSet _unknownFields;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pb::MessageParser<ErrorLog> Parser { get { return _parser; } }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pbr::MessageDescriptor Descriptor {
      get { return global::Tccc.Demo.Protobuf.ErrorLogReflection.Descriptor.MessageTypes[0]; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public ErrorLog() {
      OnConstruction();
    }

    partial void OnConstruction();

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public ErrorLog(ErrorLog other) : this() {
      logID_ = other.logID_;
      context_ = other.context_;
      stack_ = other.stack_;
      _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public ErrorLog Clone() {
      return new ErrorLog(this);
    }

    /// <summary>Field number for the "LogID" field.</summary>
    public const int LogIDFieldNumber = 1;
    private string logID_ = "";
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public string LogID {
      get { return logID_; }
      set {
        logID_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
      }
    }

    /// <summary>Field number for the "Context" field.</summary>
    public const int ContextFieldNumber = 2;
    private string context_ = "";
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public string Context {
      get { return context_; }
      set {
        context_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
      }
    }

    /// <summary>Field number for the "Stack" field.</summary>
    public const int StackFieldNumber = 3;
    private string stack_ = "";
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public string Stack {
      get { return stack_; }
      set {
        stack_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override bool Equals(object other) {
      return Equals(other as ErrorLog);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool Equals(ErrorLog other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (LogID != other.LogID) return false;
      if (Context != other.Context) return false;
      if (Stack != other.Stack) return false;
      return Equals(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override int GetHashCode() {
      int hash = 1;
      if (LogID.Length != 0) hash ^= LogID.GetHashCode();
      if (Context.Length != 0) hash ^= Context.GetHashCode();
      if (Stack.Length != 0) hash ^= Stack.GetHashCode();
      if (_unknownFields != null) {
        hash ^= _unknownFields.GetHashCode();
      }
      return hash;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override string ToString() {
      return pb::JsonFormatter.ToDiagnosticString(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void WriteTo(pb::CodedOutputStream output) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      output.WriteRawMessage(this);
    #else
      if (LogID.Length != 0) {
        output.WriteRawTag(10);
        output.WriteString(LogID);
      }
      if (Context.Length != 0) {
        output.WriteRawTag(18);
        output.WriteString(Context);
      }
      if (Stack.Length != 0) {
        output.WriteRawTag(26);
        output.WriteString(Stack);
      }
      if (_unknownFields != null) {
        _unknownFields.WriteTo(output);
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
      if (LogID.Length != 0) {
        output.WriteRawTag(10);
        output.WriteString(LogID);
      }
      if (Context.Length != 0) {
        output.WriteRawTag(18);
        output.WriteString(Context);
      }
      if (Stack.Length != 0) {
        output.WriteRawTag(26);
        output.WriteString(Stack);
      }
      if (_unknownFields != null) {
        _unknownFields.WriteTo(ref output);
      }
    }
    #endif

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public int CalculateSize() {
      int size = 0;
      if (LogID.Length != 0) {
        size += 1 + pb::CodedOutputStream.ComputeStringSize(LogID);
      }
      if (Context.Length != 0) {
        size += 1 + pb::CodedOutputStream.ComputeStringSize(Context);
      }
      if (Stack.Length != 0) {
        size += 1 + pb::CodedOutputStream.ComputeStringSize(Stack);
      }
      if (_unknownFields != null) {
        size += _unknownFields.CalculateSize();
      }
      return size;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(ErrorLog other) {
      if (other == null) {
        return;
      }
      if (other.LogID.Length != 0) {
        LogID = other.LogID;
      }
      if (other.Context.Length != 0) {
        Context = other.Context;
      }
      if (other.Stack.Length != 0) {
        Stack = other.Stack;
      }
      _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(pb::CodedInputStream input) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      input.ReadRawMessage(this);
    #else
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
            break;
          case 10: {
            LogID = input.ReadString();
            break;
          }
          case 18: {
            Context = input.ReadString();
            break;
          }
          case 26: {
            Stack = input.ReadString();
            break;
          }
        }
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
            break;
          case 10: {
            LogID = input.ReadString();
            break;
          }
          case 18: {
            Context = input.ReadString();
            break;
          }
          case 26: {
            Stack = input.ReadString();
            break;
          }
        }
      }
    }
    #endif

  }

  #endregion

}

#endregion Designer generated code

序列化操作

public static byte[] Serialize(ErrorLog log)
        {
            using (MemoryStream output = new MemoryStream())
            {
                log.WriteTo(output);
                return output.ToArray();
            }
        }

反序列化操作

ErrorLog desErrorLog= ErrorLog.Parser.ParseFrom(data);

使用特點和理解

  • protoc.exe是支持生成多語言類型,這對于跨語言的混合編程比較方便。
  • 根據上述使用步驟可以看到,必須先使用工具protoc生成目標類型,才能調用序列化和反序列化方法,這有些不符合.net平臺的編碼習慣。
  • 一堆自動生成的C#類在可維護性方面欠佳,當需要調整屬性字段時,還要通過工具重新生成,較為麻煩。

到此這篇關于Google.Protobuf工具在C#中的使用方法就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:

相關文章

  • 解析在內部循環(huán)中Continue外部循環(huán)的使用詳解

    解析在內部循環(huán)中Continue外部循環(huán)的使用詳解

    本篇文章是對在內部循環(huán)中Continue外部循環(huán)的使用進行了詳細的分析介紹,需要的朋友參考下
    2013-05-05
  • c# 抓取Web網頁數據分析

    c# 抓取Web網頁數據分析

    通過程序自動的讀取其它網站網頁顯示的信息,類似于爬蟲程序。比方說我們有一個系統(tǒng),要提取BaiDu網站上歌曲搜索排名。分析系統(tǒng)在根據得到的數據進行數據分析。為業(yè)務提供參考數據。
    2008-11-11
  • C#對WPF數據綁定的菜單插入Seperator分隔

    C#對WPF數據綁定的菜單插入Seperator分隔

    這篇文章介紹了C#對WPF數據綁定的菜單插入Seperator分隔的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • C#使用SqlDataAdapter對象獲取數據的方法

    C#使用SqlDataAdapter對象獲取數據的方法

    這篇文章主要介紹了C#使用SqlDataAdapter對象獲取數據的方法,結合實例形式較為詳細的分析了SqlDataAdapter對象獲取數據具體步驟與相關使用技巧,需要的朋友可以參考下
    2016-02-02
  • C#使用Spire.PDF實現PDF與OFD的互轉

    C#使用Spire.PDF實現PDF與OFD的互轉

    在日常辦公和電子文檔處理中,PDF和OFD是兩種最常見的電子文檔格式,本文將分享如何使用C#和Spire.PDF組件輕松實現這兩種格式的相互轉換,感興趣的小伙伴可以了解下
    2026-02-02
  • 簡單實現winform編輯器

    簡單實現winform編輯器

    這篇文章主要教大家如何簡單實現winform編輯器,功能很簡單,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-08-08
  • C#/VB.NET實現HTML轉為XML的示例代碼

    C#/VB.NET實現HTML轉為XML的示例代碼

    可擴展標記語言(XML)文件是一種標準的文本文件,它使用特定的標記來描述文檔的結構以及其他特性。本文將利用C#實現HTML轉為XML,需要的可以參考一下
    2022-06-06
  • 如何應用C#實現UDP的分包組包

    如何應用C#實現UDP的分包組包

    本篇文章小編將為大家介紹,如何應用C#實現UDP的分包組包。需要的朋友參考下
    2013-04-04
  • c#生成自定義圖片方法代碼實例

    c#生成自定義圖片方法代碼實例

    在本篇文章中我們給大家分享了關于c#生成自定義圖片方法的相關內容,有需要的朋友們可以參考下。
    2018-10-10
  • C# OpenCvSharp利用白平衡技術實現圖像修復功能

    C# OpenCvSharp利用白平衡技術實現圖像修復功能

    這篇文章主要為大家詳細介紹了C# OpenCvSharp如何利用白平衡技術實現圖像修復功能,文中的示例代碼講解詳細,希望對大家有一定的幫助
    2024-02-02

最新評論

丹阳市| 永仁县| 旺苍县| 天台县| 金门县| 同江市| 桓仁| 霍州市| 潼关县| 城固县| 平乐县| 东台市| 体育| 赤壁市| 张家界市| 张家港市| 镇坪县| 桃江县| 鄯善县| 林芝县| 新余市| 仪陇县| 武清区| 滁州市| 龙州县| 永济市| 宾阳县| 平泉县| 长汀县| 远安县| 墨竹工卡县| 镇宁| 长丰县| 河源市| 长汀县| 衡阳市| 中江县| 尼玛县| 桃园县| 台湾省| 平顺县|