質問

私はc#でreflection.emitを使用して排出しようとしています using (x) { ... } ブロック。

私がコードにある時点で、私はスタックの現在の上部を取得する必要があります。これは、Idisposableを実装するオブジェクトであり、これをローカル変数に保存し、その変数に使用するブロックを実装し、その内部にさらにいくつか追加しますコード(私はその最後の部分に対処できます。)

これが私がコンパイルしようとしたコードのサンプルC#断片です。

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

これはリフレクターでこのように見えます:

.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 ..."そこで最後に対処する方法がわかりません。

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


編集: :電子メールでコードについて尋ねられた後、ここにFluent Interfaceコードを投稿しますが、クラスライブラリの一部をつかまわない限り、誰にもあまり役に立たないでしょう。これも少しコードです。私が苦労していたコードは私の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();
}

エミットがジョンが答えたBeginexceptionBlockを吐き出すので、それが私が知る必要があることです。

上記のコードはからです loggingdecorator.cs, 、IL拡張機能はほとんどにあります ilgeneratorextensions.designer.cs, 、およびの他のファイル LVK.反射 名前空間。

役に立ちましたか?

解決

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

他のヒント

コードの例を以下に示します。

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();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top