有没有办法创建委托来获取和设置FieldInfo的值? [英] Is there a way to create a delegate to get and set values for a FieldInfo?
问题描述
对于属性,有 GetGetMethod
和 GetSetMethod
,以便我可以做到:
For properties there are GetGetMethod
and GetSetMethod
so that I can do:
Getter = (Func<S, T>)Delegate.CreateDelegate(typeof(Func<S, T>),
propertyInfo.GetGetMethod());
和
Setter = (Action<S, T>)Delegate.CreateDelegate(typeof(Action<S, T>),
propertyInfo.GetSetMethod());
但是,如何解决 FieldInfo
s ?
But how do I go about FieldInfo
s?
我不是在寻找代表 GetValue
和 SetValue
(这意味着我每次都会引用反射)
I am not looking for delegates to GetValue
and SetValue
(which means I will be invoking reflection each time)
Getter = s => (T)fieldInfo.GetValue(s);
Setter = (s, t) => (T)fieldInfo.SetValue(s, t);
但如果有一个 CreateDelegate
? 我的意思是由于分配返回值,我可以治疗分配像一个方法?如果是这样,它有一个 MethodInfo
句柄?换句话说,如何传递正确的 MethodInfo
设置并从成员字段获取值到 CreateDelegate
方法,以便我得到一个代理,我可以直接读取和写入字段
but if there is a CreateDelegate
approach here? I mean since assignments return a value, can I treat assignments like a method? If so is there a MethodInfo
handle for it? In other words how do I pass the right MethodInfo
of setting and getting a value from a member field to CreateDelegate
method so that I get a delegate back with which I can read and write to fields directly?
Getter = (Func<S, T>)Delegate.CreateDelegate(typeof(Func<S, T>), fieldInfo.??);
Setter = (Action<S, T>)Delegate.CreateDelegate(typeof(Action<S, T>), fieldInfo.??);
我可以构建表达式并编译它,但我正在寻找更简单的东西。最后,如果没有问题的回答,我不介意去表达路线,如下所示:
I can build expression and compile it, but I am looking for something simpler. In the end I don't mind going the expression route if there is no answer for the asked question, as shown below:
var instExp = Expression.Parameter(typeof(S));
var fieldExp = Expression.Field(instExp, fieldInfo);
Getter = Expression.Lambda<Func<S, T>>(fieldExp, instExp).Compile();
if (!fieldInfo.IsInitOnly)
{
var valueExp = Expression.Parameter(typeof(T));
Setter = Expression.Lambda<Action<S, T>>(Expression.Assign(fieldExp, valueExp), instExp, valueExp).Compile();
}
或者我不在之后(因为我没有看到类似的东西)?
Or am I after the nonexistent (since I have nowhere seen something like that yet) ?
推荐答案
字段访问不是通过一个方法(如getters和setter)执行的 - 它是用IL指令执行的 - 所以没有什么可以将分配给一个代表。您必须使用表达式路由来创建可以分配给代理的代码(实际上是IL)的块。
Field access isn't performed via a method (like getters and setters)--it's performed with an IL instruction--so there's nothing you can assign to a delegate. you'll have to use the expression route to create a "block" of code (effectively IL) that can be assigned to a delegate.
这篇关于有没有办法创建委托来获取和设置FieldInfo的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!