3

我想使用反射来查看 .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 文件的更好方法?

谢谢!!

4

1 回答 1

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 使用非泛型作为核心)。

于 2012-04-23T09:24:14.097 回答