c# - .NET Create struct property getter delegate -
i have method create property getter delegate:
private static delegate createpropertygetter(propertyinfo propertyinfo) { methodinfo propertygetter = propertyinfo.getgetmethod(); dynamicmethod dyngetter = new dynamicmethod ( string.concat("dm$member_getter_", propertyinfo.name), propertyinfo.propertytype, new type[1] { propertyinfo.declaringtype }, propertyinfo.declaringtype, true ); ilgenerator ilgen = dyngetter.getilgenerator(); ilgen.emit(opcodes.ldarg_0); ilgen.emitcall(propertyinfo.declaringtype.isvaluetype ? opcodes.call : opcodes.callvirt, propertygetter, null); ilgen.emit(opcodes.ret); return dyngetter.createdelegate(typeof(membergetter<,>).makegenerictype(propertyinfo.declaringtype, propertyinfo.propertytype)); }
this code work fine classes, structs throw argumentnullexception when try property value.
try changing line this:
ilgen.emit(opcodes.ldarg_0);
to this:
ilgen.emit(propertyinfo.declaringtype.isvaluetype ? opcodes.ldarga : opcodes.ldarg, 0);
this loads address of first argument (located on stack), required calling instance methods on structures.
however, i'd prefer using system.linq.expressions instead of emit.
Comments
Post a Comment