To add to the other answers, you really can insert inside the delegate if your method also returns a modified structure.
Since my IL-fu is not so big, so you do it with a simple reflection:
// the good side is that you can use generic delegates for added type safety public delegate T SetHandler<T>(T source, object value); private static SetHandler<T> GetDelegate<T>(FieldInfo fieldInfo) { return (s, val) => { object obj = s; // we have to box before calling SetValue fieldInfo.SetValue(obj, val); return (T)obj; }; }
This means that you will need to get the return value as follows:
SetHandler<MyStruct> setter = GetDelegate<MyStruct>(fi); myStruct = setter(myStruct, 111); Console.WriteLine(myStruct.myField);
But there is no need to insert it before calling setter .
Alternatively, you can pass the structure using the ref keyword, which will result in:
public delegate void SetHandler<T>(ref T source, object value); private static SetHandler<T> GetDelegate<T>(FieldInfo fieldInfo) { return (ref T s, object val) => { object obj = s; fieldInfo.SetValue(obj, val); s = (T)obj; }; } SetHandler<MyStruct> setter = GetDelegate<MyStruct>(fi); setter(ref myStruct, 111);
source share