如何使用 Google Protocol Buffer 创建通用解串器?使用 C#

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

我正在尝试使用 Google 协议缓冲区库在 C# 中进行序列化和反序列化过程。我可以使用以下代码反序列化NotificationSet.Parser.ParseJson(json); 这工作正常。

NotificationSet 是由 .proto 自动生成的文件。

但在这里你可以看到它不是通用的。因此,我需要以通用方式创建一个方法,而不是特定类型。你能就此提出建议吗?

示例:

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

问题是 TResult 是通用类型,因此无法从中获取 Parser 方法。

找到答案。

尝试使用 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;
        }
    }
}