簡體   English   中英

“范圍''引用的'System.Boolean'類型的”變量“,但未在Expression中定義

[英]“variable '' of type 'System.Boolean' referenced from scope '', but it is not defined” in Expression

我正在嘗試為(在運行時)為所有類型的委托創建包裝器創建一個方法。 這樣可以創建一種注入額外日志記錄的靈活方式(在本例中)。 在第一步中,我嘗試圍繞給定的input -argument創建try-catch包裝。

try
{
  Console.WriteLine(....);
  // Here the original call
  Console.WriteLine(....);
}
catch(Exception ex)
{
  Console.WriteLine(.....);
}

我正在使用泛型方法調用CreateWrapper2 (見下文)

private static readonly MethodInfo ConsoleWriteLine = typeof(Console).GetMethod("WriteLine", new[] { typeof(string), typeof(object[]) });

private static MethodCallExpression WriteLinExpression(string format, params object[] args)
{
    Expression[] expressionArguments = new Expression[2];
    expressionArguments[0] = Expression.Constant(format, typeof(string));
    expressionArguments[1] = Expression.Constant(args, typeof(object[]));

    return Expression.Call(ConsoleWriteLine, expressionArguments);
}

public T CreateWrapper2<T>(T input)
{
    Type type = typeof(T);

    if (!typeof(Delegate).IsAssignableFrom(type))
    {
        return input;
    }

    PropertyInfo methodProperty = type.GetProperty("Method");
    MethodInfo inputMethod = methodProperty != null ? (MethodInfo)methodProperty.GetValue(input) : null;

    if (inputMethod == null)
    {
        return input;
    }

    string methodName = inputMethod.Name;
    ParameterInfo[] parameters = inputMethod.GetParameters();
    ParameterExpression[] parameterExpressions = new ParameterExpression[parameters.Length];

    // TODO: Validate/test parameters, by-ref /out with attributes etc.

    for (int idx = 0; idx < parameters.Length; idx++)
    {
        ParameterInfo parameter = parameters[idx];
        parameterExpressions[idx] = Expression.Parameter(parameter.ParameterType, parameter.Name);
    }

    bool handleReturnValue = inputMethod.ReturnType != typeof(void);

    ParameterExpression variableExpression = handleReturnValue ? Expression.Variable(inputMethod.ReturnType) : null;
    MethodCallExpression start = WriteLinExpression("Starting '{0}'.", methodName);
    MethodCallExpression completed = WriteLinExpression("Completed '{0}'.", methodName);
    MethodCallExpression failed = WriteLinExpression("Failed '{0}'.", methodName);

    Expression innerCall = Expression.Call(inputMethod, parameterExpressions);
    LabelTarget returnTarget = Expression.Label(inputMethod.ReturnType);
    LabelExpression returnLabel = Expression.Label(returnTarget, Expression.Default(returnTarget.Type)); ;
    GotoExpression returnExpression = null;

    if (inputMethod.ReturnType != typeof(void))
    {
        // Handle return value.
        innerCall = Expression.Assign(variableExpression, innerCall);
        returnExpression = Expression.Return(returnTarget, variableExpression, returnTarget.Type);
    }
    else
    {
        returnExpression = Expression.Return(returnTarget);
    }

    List<Expression> tryBodyElements = new List<Expression>();
    tryBodyElements.Add(start);
    tryBodyElements.Add(innerCall);
    tryBodyElements.Add(completed);

    if (returnExpression != null)
    {
        tryBodyElements.Add(returnExpression);
    }

    BlockExpression tryBody = Expression.Block(tryBodyElements);
    BlockExpression catchBody = Expression.Block(tryBody.Type, new Expression[] { failed, Expression.Rethrow(tryBody.Type) });
    CatchBlock catchBlock = Expression.Catch(typeof(Exception), catchBody);
    TryExpression tryBlock = Expression.TryCatch(tryBody, catchBlock);

    List<Expression> methodBodyElements = new List<Expression>();

    if(variableExpression != null) methodBodyElements.Add(variableExpression);

    methodBodyElements.Add(tryBlock);
    methodBodyElements.Add(returnLabel);

    Expression<T> wrapperLambda = Expression<T>.Lambda<T>(Expression.Block(methodBodyElements), parameterExpressions);

    Console.WriteLine("lambda:");
    Console.WriteLine(wrapperLambda.GetDebugView());

    return wrapperLambda.Compile();
}

對於void-methods(如Action<> ),這段代碼可以滿足我的需要。 但是當有一個返回值時,我得到了從范圍''引用的'System.Boolean'類型的異常“ 變量”,但它沒有被定義

許多其他帖子談論Expression.Parameter多次為參數調用; 對我來說,這里看起來像是其他錯誤,但我找不到它。 一切順利,直到.Compile行,它崩潰了。

對於Func<int, bool> target = i => i % 2 ==0; 下面是生成的表達式的DebugView。

.Lambda #Lambda1<System.Func`2[System.Int32,System.Boolean]>(System.Int32 $i) {
    .Block() {
        $var1;
        .Try {
            .Block() {
                .Call System.Console.WriteLine(
                    "Starting '{0}'.",
                    .Constant<System.Object[]>(System.Object[]));
                $var1 = .Call LDAP.LdapProgram.<Main>b__0($i);
                .Call System.Console.WriteLine(
                    "Completed '{0}'.",
                    .Constant<System.Object[]>(System.Object[]));
                .Return #Label1 { $var1 }
            }
        } .Catch (System.Exception) {
            .Block() {
                .Call System.Console.WriteLine(
                    "Failed '{0}'.",
                    .Constant<System.Object[]>(System.Object[]));
                .Rethrow
            }
        };
        .Label
            .Default(System.Boolean)
        .LabelTarget #Label1:
    }
}

我錯過了什么? (在調試期間我試過:

  • Expression.Variable從try-body內部移動到toplevel。
  • 通過typed- Expression.Return給catch塊提供了與try-block相同的Body.Type。

看起來你沒有為block語句指定你的變量。

在錯誤中,你正在動態創建一個參數,而不給它一個名字,如果你這樣做,你會看到:

"variable 'varName' of type 'System.Boolean' referenced from scope 'varName', but it is not defined"

因此,如果您在制作表達式樹時提供您的vars名稱,以后應該可以使您的生活更輕松

        // Define the variable at the top of the block 
        // when we are returning something
        if (variableExpression != null)
        {
            block = Expression.Block(new[] { variableExpression }, methodBodyElements);
        }
        else
        {
            block = Expression.Block(methodBodyElements);
        }

        Expression<T> wrapperLambda = Expression<T>.Lambda<T>(block, parameterExpressions);

        return wrapperLambda.Compile();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM