Is there a way to create a delegate to get and set values for a FieldInfo?

后端 未结 8 2002
闹比i
闹比i 2020-12-08 08:18

For properties there are GetGetMethod and GetSetMethod so that I can do:

Getter = (Func)Delegate.CreateDelegate(typeof(         


        
8条回答
  •  抹茶落季
    2020-12-08 08:51

    No there is no easy way to create a delegate to get/set a field.

    You will have to make your own code to provide that functionallity. I would suggest two functions in a shared library to provide this.

    Using your code (in this example I only show the creation of the get-delegate):

    static public class FieldInfoExtensions
    {
        static public Func CreateGetFieldDelegate(this FieldInfo fieldInfo)
        {
            var instExp = Expression.Parameter(typeof(S));
            var fieldExp = Expression.Field(instExp, fieldInfo);
            return Expression.Lambda>(fieldExp, instExp).Compile();
        }
    }
    

    This makes it easy to create a get-delegate from a FieldInfo (assuming the field is of type int):

    Func getter = typeof(MyClass).GetField("MyField").CreateGetFieldDelegate();
    

    Or if we change your code a little bit:

    static public class TypeExtensions
    {
        static public Func CreateGetFieldDelegate(this Type type, string fieldName)
        {
            var instExp = Expression.Parameter(type);
            var fieldExp = Expression.Field(instExp, fieldName);
            return Expression.Lambda>(fieldExp, instExp).Compile();
        }
    }
    

    This makes it even more easy:

    Func getter = typeof(MyClass).CreateGetFieldDelegate("MyField");
    

    It is also possible to create these delegates using IL, but that code would be more complex and does not have much more performance, if any.

提交回复
热议问题