使用ProtoContract属性在所有类型上自动化GetProto的方法

时间:2012-04-20 17:52:04

标签: protocol-buffers protobuf-net

我想使用反射来查看.dll中的所有类型,并为任何具有ProtoContract属性的文件生成.proto文件。我将使用.proto文件生成C ++类,因此我的C#代码可以与某些C ++互操作。此代码将查看.dll以查找具有ProtoContract属性的类型,但我不知道如何将类型动态传递给GetProto()。

//get assemblies in directory.
string file = @"C:\bungie\networking\shared\online\output\bin\Test\Xetrov\Xetrov.Core\Xetrov.Core.dll";
var assembly = Assembly.LoadFile(file);
foreach (var type in assembly.GetTypes())
{
    if (!type.IsClass || type.IsNotPublic) 
    {
        continue;
    }
    //Get all the attribute for the type
    object[] attributes = type.GetCustomAttributes(true);
    //Look for the ProtoContract attribute
    if(attributes.Where(att => att is ProtoBuf.ProtoContractAttribute).Any())
    {
        // We have a type that protobuf can use, generate the .proto file
            // How to tell it what type T is??  can't use variable type
        string protoDefinition = ProtoBuf.Serializer.GetProto<T>();
    }
}

我有什么想法可以做到这一点?或者为所有类型生成.proto文件的更好方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

首先,请注意,GetProto尚未在v2中重新实现,但会在某些时候出现。所以我假设我们正在谈论v1。因此,我怀疑MakeGenericMethod是你最好的选择:

// outside loop
var method = typeof(ProtoBuf.Serializer).GetMethod("GetProto");
...
// inside loop
var proto = untyped.MakeGenericMethod(type).Invoke(null, null);

当我在v2中重新实现它时,它也将在非泛型API上可用(v2使用非泛型作为核心)。