Frequently asked by friends about how to dynamically generateCode. This function is supported by the. NET Framework. The following is a simple example.
Private void generatecode (){
/* Note: import the following namespace first
Using system. codedom
Using system. codedom. compiler;
Using Microsoft. CSHARP;
Using system. reflection;
*/
// Prepare a code compiler Unit
Codecompileunit unit = new codecompileunit ();
// Prepare the necessary namespace (this refers to the space of the class to be generated)
Codenamespace samplenamespace = new codenamespace ("xizhang.com ");
// Import necessary namespaces
Samplenamespace. Imports. Add (New codenamespaceimport ("system "));
// Prepare the definition of the class to be generated
Codetypedeclaration customerclass = new codetypedeclaration ("customer ");
// Specify this is a class
Customerclass. isclass = true;
Customerclass. typeattributes = typeattributes. Public | typeattributes. sealed;
// Put this class under this namespace
Samplenamespace. types. Add (customerclass );
// Add the namespace to the namespace set of the compiler Unit
Unit. namespaces. Add (samplenamespace );
// This is the output file
String outputfile = "customer. cs ";
// Add a field
Codememberfield field = new codememberfield (typeof (system. String), "_ id ");
Field. Attributes = memberattributes. Private;
Customerclass. members. Add (field );
// Add attributes
Codememberproperty property = new codememberproperty ();
Property. Attributes = memberattributes. Public | memberattributes. Final;
Property. Name = "ID ";
Property. hasget = true;
Property. hasset = true;
Property. type = new codetypereference (typeof (system. String ));
Property. Comments. Add (New codecommentstatement ("this is the ID property "));
Property. getstatements. Add (New codemethodreturnstatement (New codefieldreferenceexpression (New codethisreferenceexpression (), "_ id ")));
Property. setstatements. Add (New codeassignstatement (New codefieldreferenceexpression (New codethisreferenceexpression (), "_ id"), new codepropertysetvaluereferenceexpression ()));
Customerclass. members. Add (property );
// Add method (use codemembermethod) -- omitted here
// Add the constructor (use codeconstructor) -- this is omitted
// AddProgramEntry Point (using codeentrypointmethod) -- omitted here
// Add an event (use codememberevent) -- this is omitted
// Add features (use codeattributedeclaration)
Customerclass. customattributes. Add (New codeattributedeclaration (New codetypereference (typeof (serializableattribute ))));
// Generate code
Codedomprovider provider = codedomprovider. createprovider ("CSHARP ");
Codegeneratoroptions Options = new codegeneratoroptions ();
Options. bracingstyle = "C ";
Options. blanklinesbetweenmembers = true;
Using (system. Io. streamwriter Sw = new system. Io. streamwriter (outputfile )){
Provider. generatecodefromcompileunit (unit, SW, options );
}
}
The final result is