I'm using Reflection.Emit to generate getters for fields on the fly. So far, my code works in all cases I've tested except where the field isn't public. When the field isn't public, calling the delegate throws "System.NullReferenceException : Object reference not set to an instance of an object."
I'm using this code to generate: (field is a FieldInfo)
DynamicMethod dm = new DynamicMethod(String.Concat ("_Set", field.Name, "_"), typeof(void),
new Type[] { typeof(object), typeof(object) },
field.DeclaringType, true);
ILGenerator generator = dm.GetILGenerator ();
generator.Emit (OpCodes.Ldarg_0);
generator.Emit (OpCodes.Ldarg_1);
if (field.FieldType.IsValueType)
generator.Emit (OpCodes.Unbox_Any, field.FieldType);
generator.Emit (OpCodes.Stfld, field);
generator.Emit (OpCodes.Ret);
return (Action<object, object>)dm.CreateDelegate (typeof(Action<object, object>));
Are you calling with the proper parameters? For private fields you need to specify the BindingFlags.NonPublic like:
var field = this.GetType().GetField("someField", BindingFlags.NonPublic | BindingFlags.Instance);
or
var field = this.GetType().GetField("someField", BindingFlags.NonPublic | BindingFlags.Static);
Can you post the full example of the program throwing the exception?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With