11

C#でReflection.Emitを使用してusing (x) { ... }ブロックを発行しようとしています。

コードを記述している時点で、IDisposableを実装するオブジェクトであるスタックの現在の最上位を取得し、これをローカル変数に格納し、その変数にusingブロックを実装してから、その中にさらに追加する必要があります。コード(私はその最後の部分を扱うことができます。)

これは、Reflectorでコンパイルして確認しようとしたC#コードのサンプルです。

public void Test()
{
    TestDisposable disposable = new TestDisposable();
    using (disposable)
    {
        throw new Exception("Test");
    }
}

これはReflectorでは次のようになります。

.method public hidebysig instance void Test() cil managed
{
    .maxstack 2
    .locals init (
        [0] class LVK.Reflection.Tests.UsingConstructTests/TestDisposable disposable,
        [1] class LVK.Reflection.Tests.UsingConstructTests/TestDisposable CS$3$0000,
        [2] bool CS$4$0001)
    L_0000: nop 
    L_0001: newobj instance void LVK.Reflection.Tests.UsingConstructTests/TestDisposable::.ctor()
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: stloc.1 
    L_0009: nop 
    L_000a: ldstr "Test"
    L_000f: newobj instance void [mscorlib]System.Exception::.ctor(string)
    L_0014: throw 
    L_0015: ldloc.1 
    L_0016: ldnull 
    L_0017: ceq 
    L_0019: stloc.2 
    L_001a: ldloc.2 
    L_001b: brtrue.s L_0024
    L_001d: ldloc.1 
    L_001e: callvirt instance void [mscorlib]System.IDisposable::Dispose()
    L_0023: nop 
    L_0024: endfinally 
    .try L_0009 to L_0015 finally handler L_0015 to L_0025
}

Reflection.Emitを使用するときに、最後にある「.try...」の部分をどのように処理するかわかりません。

誰かが私を正しい方向に向けることができますか?


編集:メールでコードについて尋ねられた後、ここに流暢なインターフェイスコードを投稿しますが、クラスライブラリの一部を入手しない限り、誰にとってもあまり役に立たないでしょう。それも少しのコードです。私が苦労していたコードはIoCプロジェクトの一部であり、サービスのメソッド呼び出しの自動ロギングを実装するクラスを生成する必要がありました。基本的には、コードを自動生成するサービスのデコレータークラスです。

すべてのインターフェイスメソッドを実装するメソッドのメインループは次のとおりです。

foreach (var method in interfaceType.GetMethods())
{
    ParameterInfo[] methodParameters = method.GetParameters();
    var parameters = string.Join(", ", methodParameters
        .Select((p, index) => p.Name + "={" + index + "}"));
    var signature = method.Name + "(" + parameters + ")";
    type.ImplementInterfaceMethod(method).GetILGenerator()
        // object[] temp = new object[param-count]
        .variable<object[]>() // #0
        .ldc(methodParameters.Length)
        .newarr(typeof(object))
        .stloc_0()
        // copy all parameter values into array
        .EmitFor(Enumerable.Range(0, methodParameters.Length), (il, i) => il
            .ldloc_0()
            .ldc(i)
            .ldarg_opt(i + 1)
            .EmitIf(methodParameters[i].ParameterType.IsValueType, a => a
                .box(methodParameters[i].ParameterType))
            .stelem(typeof(object))
        )
        // var x = _Logger.Scope(LogLevel.Debug, signature, parameterArray)
        .ld_this()
        .ldfld(loggerField)
        .ldc(LogLevel.Debug)
        .ldstr(signature)
        .ldloc(0)
        .call_smart(typeof(ILogger).GetMethod("Scope", new[] { typeof(LogLevel), typeof(string), typeof(object[]) }))
        // using (x) { ... }
        .EmitUsing(u => u
            .ld_this()
            .ldfld(instanceField)
            .ldargs(Enumerable.Range(1, methodParameters.Length).ToArray())
            .call_smart(method)
            .EmitCatch<Exception>((il, ex) => il
                .ld_this()
                .ldfld(loggerField)
                .ldc(LogLevel.Debug)
                .ldloc(ex)
                .call_smart(typeof(ILogger).GetMethod("LogException", new[] { typeof(LogLevel), typeof(Exception) }))
            )
        )
        .ret();
}

EmitUsingは、Jonが応答したBeginExceptionBlockを吐き出すので、それを知る必要がありました。

上記のコードはLoggingDecorator.csからのものであり、IL拡張機能は主にILGeneratorExtensions.Designer.csにあり、その他のファイルはLVK.Reflection名前空間にあります。

4

2 に答える 2

11

ILGenerator.BeginExceptionBlockあなたが求めているのは何ですか?ドキュメントの例は、それが正しいアプローチであることを示唆しています...

于 2010-06-08T15:53:32.277 に答える
0

これがコードの例です。

ILGenerator ilg = ...;

// Begin the 'try' block. The returned label is at the end of the 'try' block.
// You can jump there and any finally blocks will be executed.
Label block = ilg.BeginExceptionBlock();

// ... emit operations that might throw

ilg.BeginFinallyBlock();

// ... emit operations within the finally block

ilg.EndExceptionBlock();
于 2016-04-02T19:04:07.720 に答える