简体   繁体   English

如何使用 Google 协议缓冲区创建通用反序列化器? 使用 C#

[英]How to create generic deserializer using Google Protocol Buffer? Using C#

I am trying to use Google protocol buffer library for serializing and deserialzing process in C#.我正在尝试使用 Google 协议缓冲区库在 C# 中进行序列化和反序列化过程。 I can deserialize using following code NotificationSet.Parser.ParseJson(json);我可以使用以下代码进行反序列NotificationSet.Parser.ParseJson(json); And this is working fine.这工作正常。

NotificationSet is auto generated file by.proto. NotificationSet 是由.proto 自动生成的文件。

But here you can see it is not generic.但在这里你可以看到它不是通用的。 So, instead of specif type i need to make a method in generic way.因此,我需要以通用方式创建一个方法,而不是指定类型。 Can you please advice on this?你能就此提出建议吗?

Example:例子:

public async Task<TResult> Deserialize<TResult, TValue>(TValue value)
    {
        TResult.Parser.ParseJson(value.ToString());
    }

Problem is TResult is generic type, so unable to get Parser method from that.问题是 TResult 是泛型类型,因此无法从中获取 Parser 方法。

Found an answer.找到了答案。

Try with is code to achieve generic deserialization process using google protocol buffer library.尝试使用 google 协议缓冲区库实现通用反序列化过程的代码。

 public async Task<TResult> Deserialize<TResult,TValue>(TValue value)
    {
        try
        {
            System.Type type = typeof(TResult);
            var typ = Assembly.GetExecutingAssembly().GetTypes().First(t => t.Name == type.Name);
            var descriptor = (MessageDescriptor)typ.GetProperty("Descriptor", BindingFlags.Public | BindingFlags.Static).GetValue(null, null); 
            var response = descriptor.Parser.ParseJson(value.ToString());
            return await Task.FromResult((TResult)response);


        }
        catch (Exception ex)
        {

            throw ex;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM