//创建一个代码生成器实例
CSharpCodeProvider provider = new CSharpCodeProvider();
ICodeGenerator codeGenerator = provider.CreateGenerator(codeWriter);
CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions();
//添加命名空间
CodeSnippetCompileUnit literal = new CodeSnippetCompileUnit
("using System;\nusing System.Data;\nusing System.Data.SqlClient;\n");
codeGenerator.GenerateCodeFromCompileUnit(literal,codeWriter,codeGeneratorOptions);
//命名空间以及在此命名空间下面创建一个类
CodeNamespace codeNamespace = new CodeNamespace("Codedom");
CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration();
codeTypeDeclaration.Name = "TestClass";
codeTypeDeclaration.IsClass = true;
codeTypeDeclaration.TypeAttributes = TypeAttributes.Public;
codeNamespace.Types.Add(codeTypeDeclaration);
//创建一个默认的构造函数
CodeConstructor codeConstructor = new CodeConstructor();
codeConstructor.Attributes = MemberAttributes.Public;
codeTypeDeclaration.Members.Add(codeConstructor);
//创建一个私有的字段
CodeMemberField codeMember = new CodeMemberField();
codeMember.Name = "sTest";
codeMember.Attributes = MemberAttributes.Private;
codeMember.Type = new CodeTypeReference(typeof(string));
codeTypeDeclaration.Members.Add(codeMember);
//添加一个可以操作和读取的属性
CodeMemberProperty codeMemberProperty = new CodeMemberProperty();
codeMemberProperty.Name = "Test";
codeMemberProperty.Attributes = MemberAttributes.Public;
codeMemberProperty.Type = new CodeTypeReference(typeof(string));
codeMemberProperty.GetStatements.Add
(
new CodeMethodReturnStatement
(
new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),"sTest")
)
);
codeMemberProperty.SetStatements.Add
(
new CodeAssignStatement
(
new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),"sTest"),new CodePropertySetValueReferenceExpression()
)
);
codeTypeDeclaration.Members.Add(codeMemberProperty);
//生成代码
codeGenerator.GenerateCodeFromNamespace(codeNamespace,codeWriter,codeGeneratorOptions);
codeWriter.Close();
codeStream.Close();
运行结果如下:
using System;
using System.Data;
using System.Data.SqlClient;
namespace Codedom{
public class TestClass {
private string sTest;
public TestClass() {
}
public virtual string Test {
get {
return this.sTest;
}
set {
this.sTest = value;
}
}
}
}
以上的代码理解起来并不难,只要大家看一看运行的结果就会明白了,里面具体所用到的类可以在MSDN里查到,今天暂时就写到这里吧,希望能给大家起一个抛砖引玉的作用,呵呵,如果想和我交流的朋友,可以发邮件到我的邮箱:,最后告诉大家:掌握CodeDom并不难。