Skip to content

Instantly share code, notes, and snippets.

@nocd5
Created July 18, 2015 20:33
Show Gist options
  • Save nocd5/6dd66440aec2ab78f476 to your computer and use it in GitHub Desktop.
Save nocd5/6dd66440aec2ab78f476 to your computer and use it in GitHub Desktop.
CSharpCodeProviderサンプル

呼び出し側

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;

namespace CSharpCodeProviderSample
{
    class Program
    {
        static void Main(string[] args)
        {
            using (CodeDomProvider codeDomProvider = new CSharpCodeProvider())
            {
                CompilerParameters compilerParameters = new CompilerParameters();
                // .exe作らずメモリ上で処理
                compilerParameters.GenerateInMemory = true;

                // ファイルの読み込み
                CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromFile(compilerParameters, "Sample.cs");

                Assembly assembly = compilerResults.CompiledAssembly;

                // インスタンスの作成
                Type dynamicClassT = assembly.GetType("DynamicClass");
                dynamic dynamicClass = Activator.CreateInstance(dynamicClassT);

                // プロパティ取得、メソッド実行
                Console.WriteLine(dynamicClass.Foo);
                Console.WriteLine(dynamicClass.Bar(1, 2));
                Console.WriteLine(dynamicClass.Hoge("だー"));
            }

            Console.ReadKey();
        }
    }
}

呼び出される側

using System;

public class DynamicClass
{
    public String Foo = "いくぞー";
    public Double Bar (Double a, Double b)
    {
        Console.WriteLine(a);
        Console.WriteLine(b);
        return a+b;
    }
    public String Hoge (String s)
    {
        return s + "!!!";
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment