読者です 読者をやめる 読者になる 読者になる

無気力生活 (ノ ´ω`)ノ ~゜

脱力系エンジニア。てきとーに生きてます。

RoslynかわいいよRoslyn

サンプル見てて大層感動したので、いじってみた。
解説は後日。

using System;
using System.Collections.Generic;
using System.Linq;
using Roslyn.Compilers.CSharp;
namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            SyntaxTree tree = SyntaxTree.ParseCompilationUnit(
                @"
                using System;
                using System.Collections.Generic;
                using System.Linq;
                using System.Text;

                namespace Roslyn_Sample
                {
                    public class Person
                    {
                        public string Name { get; private set; }
                        public Person(string name)
                        {
                            Name = name;
                        }

                        public string Speak()
                        {
                            return string.Format(""Hello My Name is {0}"", Name);
                        }
                    }
                }");

            // 外部ファイルから読み込む用
            // var code = new StreamReader("../../Person.cs").ReadToEnd();
            // SyntaxTree tree = SyntaxTree.ParseCompilationUnit(code);

            var root = (CompilationUnitSyntax)tree.GetRoot();
            root.Usings.ForEach(x => Console.WriteLine("Using Block: {0}", x.Name));
            root.Members.ForEach(member =>
            {
                if (member is NamespaceDeclarationSyntax) (member as NamespaceDeclarationSyntax).Members.ForEach(nsM => {
                    if (nsM is ClassDeclarationSyntax) (nsM as ClassDeclarationSyntax).Members.ForEach(csM => {

                        if (csM is ConstructorDeclarationSyntax)
                            Console.WriteLine("Constructor:\n " + (csM as ConstructorDeclarationSyntax).GetText());
                        if (csM is PropertyDeclarationSyntax)
                            Console.WriteLine("Property:\n " + (csM as PropertyDeclarationSyntax).GetText());
                        if (csM is MethodDeclarationSyntax)
                            Console.WriteLine("Method:\n" + (csM as MethodDeclarationSyntax).GetText());
                        if (csM is FieldDeclarationSyntax)
                            Console.WriteLine("Field:\n" + (csM as FieldDeclarationSyntax).GetText());
                    });
                });
            });
            Console.ReadKey();
        }
    }

    // foreachなんて書いてられっかヽ(`Д´)ノ
    public static class Extentions
    {
        public static void ForEach<T>(this IEnumerable<T> src, Action<T> func)
        {
            IEnumerator<T> enumrator = src.GetEnumerator();
            while (enumrator.MoveNext()) func(enumrator.Current);
        }
    }
}