How to build CodeCompileUnit from source code?
What is the best way to parse a C# source开发者_开发技巧 code(s)?
Is CodeCompileUnit a correct selection? and howto?
Thanks
You've got that backwards, CodeCompileUnit is there to generate source code. If you already have the source code then you only need a class that inherits CodeDomProvider to compile the code. Like Microsoft.CSharp.CSharpCodeProvider or Microsoft.VisualBasic.VBCodeProvider.
There are some odds that you are asking about parsing an existing source code file. That's what the System.CodeDom.Compiler.CodeParser was intended to do. There are no existing concrete implementations of that abstract class, there will never be any. This blog post explains why.
You can do it with CodeSnippetCompileUnit which is a subclass of CodeCompileUnit:
string source = @"
using System;
namespace SomeNamespace
{
public class Class0
{
}
}";
var csu0 = new CodeSnippetCompileUnit(curSource);
Additional Info:
If you have multiple units you can put them together to generate an assembly:
CodeDomProvider provider = new CSharpCodeProvider();
CompilerResults results = provider.CompileAssemblyFromDom(new CompilerParameters(), csu0, csu1 /*arbitrary number*/);
Of course it it possible that classes from all of these CodeSnippetCompileUnit reference each other.
Your question is kind of vague. Are you looking for a tutorial? Do you have a specific task you are trying to implement? Specific questions are the essence of Stackoverflow. That aside, I'll just give you some places that may be helpful for starting out:
- MSDN documentation on CodeDOM
- Dynamic Code Integration with CodeDom
- CodeDOM Assistant
精彩评论