예제 #1
0
파일: FAQ.cs 프로젝트: Rickinio/roslyn
        public void InsertLoggingStatements()
        {
            var tree = SyntaxFactory.ParseSyntaxTree(@"
class Program
{
    static void Main()
    {
        System.Console.WriteLine();
        int total = 0;
        for (int i=0; i < 5; ++i)
        {
            total += i;
        }
        if (true) total += 5;
    }
}");
            SyntaxNode oldRoot = tree.GetRoot();
            var rewriter = new ConsoleWriteLineInserter();
            SyntaxNode newRoot = rewriter.Visit(oldRoot);
            newRoot = newRoot.NormalizeWhitespace(); // fix up the whitespace so it is legible.

            var newTree = SyntaxFactory.SyntaxTree(newRoot, path: "MyCodeFile.cs", encoding: Encoding.UTF8);
            var compilation = CSharpCompilation.Create("MyCompilation")
                .AddReferences(Mscorlib)
                .AddSyntaxTrees(newTree);

            string output = Execute(compilation);
            Assert.Equal(@"
0
1
3
6
10
15
", output);
        }
예제 #2
0
        public void InsertLoggingStatements()
        {
            var tree = SyntaxTree.ParseText(@"
            class Program
            {
            static void Main()
            {
            System.Console.WriteLine();
            int total = 0;
            for (int i=0; i < 5; ++i)
            {
            total += i;
            }
            if (true) total += 5;
            }
            }");
            SyntaxNode oldRoot = tree.GetRoot();
            var rewriter = new ConsoleWriteLineInserter();
            SyntaxNode newRoot = rewriter.Visit(oldRoot);
            newRoot = (SyntaxNode)newRoot.Format(FormattingOptions.GetDefaultOptions()).GetFormattedRoot(); // Format the new root.

            var newTree = SyntaxTree.Create((CompilationUnitSyntax)newRoot, "MyCodeFile.cs");
            var compilation = Compilation.Create("MyCompilation")
                .AddReferences(MetadataReference.CreateAssemblyReference("mscorlib"))
                .AddSyntaxTrees(newTree);

            string output = Execute(compilation);
            Assert.AreEqual(@"
            0
            1
            3
            6
            10
            15
            ", output);
        }