动态属性设置器通过表达式不起作用

时间:2014-03-16 14:30:31

标签: c# lambda expression

您好我在控制台应用程序中运行它时遵循完美的工作代码,但它在实际应用程序中失败,并且“指定的强制转换无效”。在lambda_method(Closure,Object,Object),有人知道这是根本原因吗?

    public class Base
    {

    }

    public class Test:Base
    {
        public string TestProp { get; set; }
    }

    static void Main(string[] args)
    {
        Base test = new Test();
        var prop=test.GetType().GetProperty("TestProp");
        var method = BuildSetAccessor(prop.SetMethod);
        method(test, "sa");
    }

    static Action<object, object> BuildSetAccessor(MethodInfo method)
    {

        var obj = Expression.Parameter(typeof(object), "o");
        var value = Expression.Parameter(typeof(object));

        Expression<Action<object, object>> expr =
            Expression.Lambda<Action<object, object>>(
                Expression.Call(
                    Expression.Convert(obj, method.DeclaringType),
                    method,
                    Expression.Convert(value, method.GetParameters()[0].ParameterType)),
                obj, value);


        return expr.Compile();
}

1 个答案:

答案 0 :(得分:1)

目前这不是答案,但我建议您将代码更改为以下内容:

static Action<TOb, TPar> BuildSetAccessor<TOb, TPar>(MethodInfo method)
{
    var obj = Expression.Parameter(method.DeclaringType, "o");
    var value = Expression.Parameter(method.GetParameters()[0].ParameterType);

    if (method.GetParameters().Length > 1)
        throw new ArgumentException("Method with more than 1 parameters is not supported");

    LambdaExpression expr =
        Expression.Lambda(
            Expression.Call(
                obj,
                method,
                value),
            obj, value);

    var compiled = expr.Compile();
    return new Action<TOb, TPar>((o, p) => compiled.DynamicInvoke(o, p));
}

用法:

var method = BuildSetAccessor<Base, object>(prop.SetMethod);
method(test, "1");

我认为这种方法比在LINQ查询中转换参数更好,因为生成的异常信息更详细。