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 に答える