For properties there are GetGetMethod
and GetSetMethod
so that I can do:
Getter = (Func)Delegate.CreateDelegate(typeof(
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.