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



我正在尝试使用Google协议缓冲库在C#中序列化和取消序列化进程。我可以使用下面的代码NotificationSet.Parser.ParseJson(json);进行反序列化,这很好。

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

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

示例:

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

问题是TResult是泛型类型,所以无法从中获取Parser方法。

找到了答案。

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

最新更新