[英]Dynamic property setter via expressions is not working
Hi I have following perfectly working code when I run it in console application but it fails in real app with exeption "Specified cast is not valid." 嗨,当我在控制台应用程序中运行该代码时,我遵循了可以正常工作的代码,但在真实应用程序中却失败了,提示“指定的转换无效”。 at lambda_method(Closure , Object , Object ), do any one knows that is root cause for this ? 在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();
}
This is not the answer at the moment, but I would recommend you to change your code to something like this: 目前尚无答案,但我建议您将代码更改为以下形式:
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));
}
And usage: 和用法:
var method = BuildSetAccessor<Base, object>(prop.SetMethod);
method(test, "1");
I think this approach is better then casting parameters in LINQ query because generated exception info is more detailed. 我认为这种方法比在LINQ查询中强制转换参数更好,因为生成的异常信息更加详细。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.