有没有办法创建一个委托来获取和设置 FieldInfo 的值?

Is there a way to create a delegate to get and set values for a FieldInfo?(有没有办法创建一个委托来获取和设置 FieldInfo 的值?)

本文介绍了有没有办法创建一个委托来获取和设置 FieldInfo 的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于属性有 GetGetMethodGetSetMethod 这样我就可以做到:

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 呢?

But how do I go about FieldInfos?

我不是在寻找 GetValueSetValue 的委托(这意味着我每次都会调用反射)

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.??);

我可以构建表达式并编译它,但我正在寻找更简单的东西.最后问的问题没有答案我也不介意走表达路线,如下图:

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) ?

推荐答案

字段访问不是通过方法(如 getter 和 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 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:有没有办法创建一个委托来获取和设置 FieldInfo 的值?

基础教程推荐