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

后端 未结 8 2001
闹比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:36

    I'm not aware if you would use Expression, then why avoiding reflection? Most operations of Expression rely on reflection.

    GetValue and SetValue themself are the get method and set method, for the fields, but they are not for any specific field.

    Fields are not like properties, they are fields, and there's no reason to generate get/set methods for each one. However, the type may vary with different field, and thus GetValue and SetValue are defined the parameter/return value as object for variance. GetValue is even a abstract method, that is, for every class(still reflection) overriding it, must be within the identical signature.

    If you don't type them, then the following code should do:

    public static void SomeMethod(FieldInfo fieldInfo) {
        var Getter=(Func)fieldInfo.GetValue;
        var Setter=(Action)fieldInfo.SetValue;
    }
    

    but if you want, there's a constrained way:

    public static void SomeMethod(FieldInfo fieldInfo)
        where S: class
        where T: class {
        var Getter=(Func)fieldInfo.GetValue;
        var Setter=(Action)fieldInfo.SetValue;
    }
    

    For the reason that the Getter still be Func, you might want to have a look of:

    Covariance and Contravariance in C#, Part Three: Method Group Conversion Variance on Mr. Lippert's blog.

提交回复
热议问题