就像是:
Type targetType = typeof(MyClass);
var obj = Expression.Variable(targetType);
var creatorExpression = Expression.New(targetType);
var assign = Expression.Assign(obj, creatorExpression);
var prop = Expression.PropertyOrField(obj, "MyProp1");
var value = Expression.Constant(5);
var member = Expression.Assign(prop, value);
var block = Expression.Block(new[] { obj }, creatorExpression, assign, member);
你必须记住那Expression.New(targetType)
是new something()
,所以如果你直接在其他地方使用它,你每次都在重新创建对象。你不想要:
new MyClass().MyProp1 = 5;
new MyClass().MyProp2 = 6;
你要
var obj = new MyClass(); // assign + creatorExpression
obj.MyProp1 = 5; // member + prop + value
obj.MyProp2 = 6; // not in the example
如果您知道您正在访问的属性/字段是您可以使用的属性或字段Expression.Property
或Expression.Field
。两者都接受string
作为属性/字段名称或PropertyInfo
/MethodInfo
可以通过反射获得。
如果您有一个执行分配的函数并返回一个带有分配的块,您可以将obj
表达式传递给它,例如:
BlockExpression MakeSomeAssignments(ParameterExpression obj, Expression value1, int value2)
{
var prop1e = Expression.PropertyOrField(obj, "MyProp1");
var member1e = Expression.Assign(prop1e, value1e);
var prop2e = Expression.PropertyOrField(obj, "MyProp2");
var value2e = Expression.Constant(value2);
var member2e = Expression.Assign(prop2e, value2e);
return new Expression.Block(member1e, member2e);
}