对于那些正在或曾经对解决方案感兴趣的人:
ParameterExpression target = Expression.Parameter(typeof(object), "target");
ParameterExpression result = Expression.Parameter(typeof(object), "result");
CallSiteBinder getName = Binder.GetMember(
CSharpBinderFlags.None, "Name", typeof(Program),
new CSharpArgumentInfo[] {
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
}
);
CallSiteBinder getSurname= Binder.GetMember(
CSharpBinderFlags.None, "Surname", typeof(Program),
new CSharpArgumentInfo[] {
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
}
);
BlockExpression block = Expression.Block(
new[] { result },
Expression.Assign(
result,
Expression.Call(typeof(string).GetMethod("Concat", new Type[] { typeof(object[]) }),
Expression.NewArrayInit(typeof(object),
Expression.Dynamic(getName, typeof(object), target),
Expression.Constant(" ", typeof(object)),
Expression.Dynamic(getSurname, typeof(object), target)
)
)
)
);
Func<dynamic, object> myFunc = Expression.Lambda<Func<dynamic, object>>(block, target).Compile();
这正是我正在做的事情:
- 创建了一个
CallSiteBinder
获取动态属性的值Name
作为参数传递的动态对象的
- 创建了一个
CallSiteBinder
获取动态属性的值Surname
作为参数传递的动态对象的
- 调用了该方法
string.Concat(params object[] args)
。为此,我需要将我的参数作为数组发送object
。我正在使用以下值创建数组getName
, " "
, and getSurname
.
我使用以下答案作为指导和参考:
C# 4 表达式树中的“动态” https://stackoverflow.com/questions/3562088/c-sharp-4-dynamic-in-expression-trees
通过上述方法,人们可以做这样的事情:
dynamic person = new ExpandoObject();
person.Name = "Matt";
person.Surname = "Smith";
object value = myFunc(person);
Console.WriteLine(value); //Will print out "Matt Smith"
//Internally it just calls:
//string.Concat(new object[] { person.Name, " ", person.Surname });