c# - How return struct object in MSIL? -
i want set struct field value , return struct instance. code working in classtype, error on structtype.
[create setter]
public static dynamicmembersetter createfieldsetter(fieldinfo fieldinfo, type declaringtype = null) { if(declaringtype == null) declaringtype = fieldinfo.reflectedtype; var emit = new emithelper(types.object, dynamicsetmemberparams, declaringtype); var isstatic = fieldinfo.isstatic; if(!isstatic) { emit.declarelocal(declaringtype); emit.ldarg_0 .casttype(declaringtype) .stloc_0 .ldloc_0 .end(); } var changetypemethod = typeof(convert).getmethod("changetype", new type[] { types.object, types.type }); var gettypefromhandlemethod = typeof(type).getmethod("gettypefromhandle", new type[] { typeof(runtimetypehandle) }); emit.ldarg_1 .ldtoken(fieldinfo.fieldtype) .call(gettypefromhandlemethod) .call(changetypemethod) .casttype(fieldinfo.fieldtype) .end(); emit.stfld(isstatic, fieldinfo) .end(); if(isstatic) { emit.ldnull .end(); } else { emit.ldloc_0 .boxifvaluetype(declaringtype) .end(); } emit.ret(); return emit.createdelegate<dynamicmembersetter>(); }
[unit test]
[testmethod()] public void createfieldsettertest() { var m = new fields.model() { public = "xs" }; // success assert.areequal(m, dynamicfactory.createfieldsetter(fields.members.public)(m, "a")); assert.areequal(m, dynamicfactory.createfieldsetter(fields.members.private)(m, "b")); assert.areequal("a", m.public); assert.areequal("b", dynamicfactory.createfieldgetter(fields.members.private)(m)); var stm = new fields.structmodel() { field = "5" }; var v = (fields.structmodel)dynamicfactory.createfieldsetter(stm.gettype().getfield("field"))(stm, "xx"); //- fail,the field "5" value. why?! assert.areequal("xx", v.field); }
i want achieve effect, not know how achieve, hoping help.
Comments
Post a Comment