喜歡的東西:
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);
}
優秀。謝謝。它將新實例分配給我缺少的變量。許多通過文檔,我仍然錯過了'Expression.Variable'方法。非常感謝 – JRoughan