相关疑难解决方法(0)

使用FieldInfo.SetValue和LINQ表达式在结构中设置字段

我想使用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, …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection linq-expressions

4
推荐指数
1
解决办法
651
查看次数

标签 统计

.net ×1

c# ×1

linq-expressions ×1

reflection ×1