CodeDOM

The .NET Framework includes a mechanism called the Code Document Object Model (CodeDOM) that enables developers of programs that emit source code to generate source code in multiple programming languages at run time, based on a single model that represents the code to render.

To represent source code, CodeDOM elements are linked to each other to form a data structure known as a CodeDOM graph, which models the structure of some source code.

The System.CodeDom namespace defines types that can represent the logical structure of source code, independent of a specific programming language. The System.CodeDom.Compiler namespace defines types for generating source code from CodeDOM graphs and managing the compilation of source code in supported languages. Compiler vendors or developers can extend the set of supported languages.

Language-independent source code modeling can be valuable when a program needs to generate source code for a program model in multiple languages or for an uncertain target language. For example, some designers use the CodeDOM as a language abstraction interface to produce source code in the correct programming language, if CodeDOM support for the language is available.

The .NET Framework includes code generators and code compilers for C#, JScript, and Visual Basic.

 

生成代码
Stream stream  =  File.Open( " Test.cs " , FileMode.Create);
StreamWriter sw 
=   new  StreamWriter(stream);

//  provides access to instances of the C# code generator and code compiler
CSharpCodeProvider provider  =   new  CSharpCodeProvider();
//  defines an interface for generating code
ICodeGenerator codeGenerator  =  provider.CreateGenerator(sw);
//  represents a set of options used by a code generator
CodeGeneratorOptions codeGeneratorOptions  =   new  CodeGeneratorOptions();

//  "Block": braces start on the same line as the statement or declaration that they are associated with
//  "C": braces start on the line following the statement or declaration that they are associated with
codeGeneratorOptions.BracingStyle  =   " C " ;

StringBuilder namespaces 
=   new  StringBuilder();
namespaces.AppendLine(
" using System; " );
namespaces.AppendLine(
" using System.Collections.Generic; " );
namespaces.AppendLine(
" using System.Text; " );
//  represents a literal code fragment that can be compiled
CodeSnippetCompileUnit literal  =   new  CodeSnippetCompileUnit(namespaces.ToString());
codeGenerator.GenerateCodeFromCompileUnit(literal, sw, codeGeneratorOptions);

//  represents a namespace declaration
CodeNamespace codeNamespace  =   new  CodeNamespace( " MyNamespace " );
//  represents a type declaration for a class, structure, interface, or enumeration
CodeTypeDeclaration codeTypeDeclaration  =   new  CodeTypeDeclaration();
codeTypeDeclaration.Name 
=   " MyClass " ;
codeTypeDeclaration.IsClass 
=   true ;
codeTypeDeclaration.TypeAttributes 
=  TypeAttributes.Public;
codeNamespace.Types.Add(codeTypeDeclaration);

//  represents a declaration for an instance constructor of a type
CodeConstructor codeConstructor  =   new  CodeConstructor();
codeConstructor.Attributes 
=  MemberAttributes.Public;
codeTypeDeclaration.Members.Add(codeConstructor);

//  represents a declaration for a field of a type
CodeMemberField codeMemberField  =   new  CodeMemberField();
codeMemberField.Name 
=   " _name " ;
codeMemberField.Attributes 
=  MemberAttributes.Private;
codeMemberField.Type 
=   new  CodeTypeReference( typeof ( string ));
codeTypeDeclaration.Members.Add(codeMemberField);

//  represents a declaration for a property of a type
CodeMemberProperty codeMemberProperty  =   new  CodeMemberProperty();
codeMemberProperty.Name 
=   " Name " ;
codeMemberProperty.Attributes 
=  MemberAttributes.Public  |  MemberAttributes.Final;
codeMemberProperty.Type 
=   new  CodeTypeReference( typeof ( string ));

//  represents a reference to the current local class instance
CodeExpression currentInstance  =   new  CodeThisReferenceExpression();
//  represents a reference to a field
CodeExpression field  =   new  CodeFieldReferenceExpression(currentInstance,  " _name " );

//  represents a return value statement
CodeStatement getStatement  =   new  CodeMethodReturnStatement(field);
codeMemberProperty.GetStatements.Add(getStatement);

//  represents the value argument of a property set method call within a property set method
CodeExpression value  =   new  CodePropertySetValueReferenceExpression();
//  represents a simple assignment statement
CodeStatement setStatement  =   new  CodeAssignStatement(field, value);
codeMemberProperty.SetStatements.Add(setStatement);
codeTypeDeclaration.Members.Add(codeMemberProperty);

//  generates code for the specified Code Document Object Model (CodeDOM) namespace
//  and outputs it to the specified text writer using the specified options
codeGenerator.GenerateCodeFromNamespace(codeNamespace, sw, codeGeneratorOptions);

sw.Close();
stream.Close();

 

运行代码
string  code  =   @"
    using System;

    namespace MyNamespace
    {
        public class MyClass
        {
            private string _name;

            public MyClass(string name)
            {
                this._name = name;
            }

            public void MyMethod()
            {
                Console.WriteLine(_name);
            }
        }
    }
    
" ;

// Stream stream = File.Open("Test.cs", FileMode.Open);
// StreamReader sr = new StreamReader(stream);
// string code = sr.ReadToEnd();

CSharpCodeProvider provider 
=   new  CSharpCodeProvider();
//  Defines an interface for invoking compilation of source code
//  or a CodeDOM tree using a specific compiler
ICodeCompiler compiler  =  provider.CreateCompiler();

//  represents the parameters used to invoke a compiler
CompilerParameters compilerParameters  =   new  CompilerParameters();
compilerParameters.ReferencedAssemblies.Add(
" System.dll " );
compilerParameters.GenerateInMemory 
=   true ;
// compilerParameters.OutputAssembly = "Test";

//  represents a literal code fragment that can be compiled
CodeSnippetCompileUnit csc  =   new  CodeSnippetCompileUnit(code);
CompilerResults cr 
=  compiler.CompileAssemblyFromDom(compilerParameters, csc);

Type type 
=  cr.CompiledAssembly.GetType( " MyNamespace.MyClass " );

//  locates the specified type from this assembly and creates an instance of
//  it using the system activator, with optional case-sensitive search and having
//  the specified culture, arguments, and binding and activation attributes
object  instance  =  cr.CompiledAssembly.CreateInstance(
    
" MyNamespace.MyClass " // the System.Type.FullName of the type to locate
     false // ignoreCase
    BindingFlags.Default,
    
null ,
    
new   object [] {  " Clotho "  },  // args
    CultureInfo.CurrentCulture,
    
null );

type.InvokeMember(
    
" MyMethod " ,
    BindingFlags.Instance 
|  BindingFlags.Public  |  BindingFlags.InvokeMethod,
    
null ,
    instance,
    
null );

 

转载于:https://www.cnblogs.com/live41/archive/2009/11/29/1612923.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值