技術をかじる猫

適当に気になった技術や言語、思ったこと考えた事など。

文字列をコンパイルして実行してみる

適当にネット漁ってたら面白そうなAPI落ちてたからやってみた。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

namespace CodeRunner
{
    class Program
    {
        const string Code = @"using System;
namespace SampleSpace
{
  public class SampleClass
  {
    public void SampleMethod()
    {
        Console.WriteLine(" + "\"Sample Code\"" + @");
    }
  }
}";
        static void Main(string[] args)
        {
            /* コンパイラとか用意 */
            CodeDomProvider provider = new CSharpCodeProvider();
            ICodeCompiler compiler = provider.CreateCompiler();
            CompilerParameters cp = new CompilerParameters();

            /* メモリに展開 */
            cp.GenerateInMemory = true;

            /* コンパイル */
            CompilerResults cr = compiler.CompileAssemblyFromSource(cp, Code);

            /* アセンブリとしてアサイン */
            Assembly asm = cr.CompiledAssembly;

            /* クラスを取り出してインスタンス作成 */
            Type sampleClass = asm.GetType("SampleSpace.SampleClass");
            Object o = Activator.CreateInstance(sampleClass);

            /* メソッド取り出して実行 */
            MethodInfo method = sampleClass.GetMethod("SampleMethod");
            method.Invoke(o, null);
        }
    }
}

自分で言うのもあれだがきめぇw