Sunday 15 September 2013

c# - Generating IL Upcodes to insert value to dictionary -



c# - Generating IL Upcodes to insert value to dictionary -

given next class

public class ogrentity { public ogrentity() { properties = new dictionary<string, object>(); } public dbgeometry ogr_geometry { get; set; } public int ogr_fid { get; set; } public dictionary<string, object> properties; }

i trying create dynamic properties on class inhering above class base.

public static typebuilder createtypebuilder<t>( string assemblyname, string modulename, string typename) { typebuilder typebuilder = appdomain .currentdomain .definedynamicassembly(new assemblyname(assemblyname), assemblybuilderaccess.run) .definedynamicmodule(modulename) .definetype(typename, typeattributes.public,typeof(t)); typebuilder.definedefaultconstructor(methodattributes.public); homecoming typebuilder; } public static void createdictionarywrappingproperty(typebuilder builder, string propertyname, type propertytype) { const string setterprefix = "set_"; // dictionary store. var dicttype = typeof(dictionary<string, object>); var dict = typeof(ogrentity).getproperty("properties"); var addmethod = dicttype.getmethod("add"); // generate property propertybuilder propertybuilder = builder.defineproperty( propertyname, propertyattributes.hasdefault, propertytype, null); // property getter , setter attributes. methodattributes propertymethodattributes = methodattributes.public | methodattributes.specialname | methodattributes.hidebysig; // define setter method. methodbuilder settermethod = builder.definemethod( string.concat(setterprefix, propertyname), propertymethodattributes, null, new type[] { propertytype }); ilgenerator setterilcode = settermethod.getilgenerator(); //what il code need next method: //set{ this.properties.add(propertyname,value); } //what il code need getter //get{ if(this.properties.containskey(propertyname)) // homecoming this.properties[propertyname] //cast right type also; // homecoming null; // } propertybuilder.setsetmethod(settermethod); }

test:

typebuilder builder = program.createtypebuilder<ogrentity>( "mydynamicassembly", "mymodule", "mytype"); program.createdictionarywrappingproperty(builder, "uuid", typeof(string)); type resulttype = builder.createtype();

compile c# code want. disassemble resulting binary. teach opcodes need emit.

c# .net

No comments:

Post a Comment