CODEDOM动态编译相关资料

http://www.cnblogs.com/lichdr/category/12610.html

http://www.manbu.net/Lib/Class2/Sub1/1/2.asp 

   //保存源代码的流。
   Stream codeStream = File.Open("Test.cs",FileMode.Create);
   StreamWriter codeWriter = new StreamWriter(codeStream);

   //创建一个代码生成器实例
   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);

你可能感兴趣的:(code)