日期:2010-05-04 浏览次数:20437 次
//创建一个代码生成器实例
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{