2011-03-24 115 views
0

我試圖更新現有的C#代碼。該代碼使用ICSharpCode.NRefactory.IParser進行解析。我的系統正在廣泛使用ICompilationUnit來探索現有的代碼。如何從ICompilationUnit(ICSharpCode)生成C#代碼

現在,我想添加一個方法到現有的文件,並將其保存回磁盤作爲C#代碼。到目前爲止,我有:

CompilationUnit compilationUnit = GetCompilationUnit(); 
var visitor = new NRefactoryASTConvertVisitor(new ParseProjectContent()); 
compilationUnit.AcceptVisitor(visitor, null); 
IMethod method = //GetMethod from otherplace 
visitor.Cu.Classes[0].Methods.Add(method); 
// How the updated visitor.Cu be transformed to C# code 

我希望做的是從visitor.Cu生成C#代碼。有沒有辦法從ICompilationUnit生成C#代碼?

回答

2

您正在將方法添加爲IMethod - IMethod只是將方法表示爲一個DOM實體以及有關其簽名的一些信息(不帶任何代碼) - 因此我不瞭解您將如何生成它的C#代碼...

(除非你的意思是爲方法的簽名生成代碼?在這種情況下,您應該查看ICSharpCode.SharpDevelop.Dom.Refactoring.CodeGenerator類的DOM-> AST轉換方法ConvertMember(IMethod m, ClassFinder targetContext))。

CompilationUnit,但是,是在代碼文件的抽象語法樹,並且可以容易地轉換回C#/使用CSharpOutputVisitor和VBNetOutputVisitor類VB.NET代碼。

您可以將表示方法代碼的MethodDeclaration添加到表示原始文件中的某個類的TypeDefinition,然後使用前面提到的輸出訪問者用插入的新方法生成代碼。

爲了您的舒適,我附加PrettyPrint擴展方法上的inode轉換成代碼時是有用的:

public static string PrettyPrint(this INode code, LanguageProperties language) 
    { 
     if (code == null) return string.Empty; 
     IOutputAstVisitor csOutVisitor = CreateCodePrinter(language); 
     code.AcceptVisitor(csOutVisitor, null); 
     return csOutVisitor.Text; 
    } 

    private static IOutputAstVisitor CreateCodePrinter(LanguageProperties language) 
    { 
     if (language == LanguageProperties.CSharp) return new CSharpOutputVisitor(); 
     if (language == LanguageProperties.VBNet) return new VBNetOutputVisitor(); 
     throw new NotSupportedException(); 
    } 

    public static string ToCSharpCode(this INode code) 
    { 
     return code.PrettyPrint(LanguageProperties.CSharp); 
    }