【发布时间】:2015-08-22 16:35:21
【问题描述】:
我想使用 LINQ 表达式设置私有字段。我有这个代码:
//parameter "target", the object on which to set the field `field`
ParameterExpression targetExp = Expression.Parameter(typeof(object), "target");
//parameter "value" the value to be set in the `field` on "target"
ParameterExpression valueExp = Expression.Parameter(typeof(object), "value");
//cast the target from object to its correct type
Expression castTartgetExp = Expression.Convert(targetExp, type);
//cast the value to its correct type
Expression castValueExp = Expression.Convert(valueExp, field.FieldType);
//the field `field` on "target"
MemberExpression fieldExp = Expression.Field(castTartgetExp, field);
//assign the "value" to the `field`
BinaryExpression assignExp = Expression.Assign(fieldExp, castValueExp);
//compile the whole thing
var setter = Expression.Lambda<Action<object, object>> (assignExp, targetExp, valueExp).Compile();
这编译了一个接受两个对象的委托:目标和值:
setter(someObject, someValue);
type变量指定目标的Type,field变量是FieldInfo指定要设置的字段。
这对引用类型很有用,但是如果目标是一个结构,那么这个东西会将目标作为副本传递给 setter 委托并在副本上设置值,而不是像在原始目标上设置值我想。 (至少我认为是这样的。)
另一方面,
field.SetValue(someObject, someValue);
工作得很好,即使是结构。
为了使用编译的表达式设置目标的字段,我能做些什么吗?
【问题讨论】:
-
因为你不能使用
ref,唯一的办法就是分配返回值。
标签: c# .net reflection linq-expressions