Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection.Emit private field/property access

Tags:

c#

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>));
like image 620
Nol Avatar asked Nov 03 '22 19:11

Nol


1 Answers

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?

like image 69
user1494736 Avatar answered Nov 15 '22 16:11

user1494736