첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ 런타임에서 C# 코드를 동적으로 컴파일하기

----------------------------------------------------------------------------------------------------


TestProject.zip


Program.cs

 

 

using Microsoft.CodeAnalysis;

using Microsoft.CodeAnalysis.CSharp;

using Microsoft.CodeAnalysis.Emit;

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Reflection;

 

namespace TestProject

{

    /// <summary>

    /// 프로그램

    /// </summary>

    class Program

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Static

        //////////////////////////////////////////////////////////////////////////////// Private

 

        #region 프로그램 시작하기 - Main()

 

        /// <summary>

        /// 프로그램 시작하기

        /// </summary>

        private static void Main()

        {

            #region C# 코드를 설정한다.

 

            string code = @"

using System;

 

namespace TestProject

{

    public class Writer

    {

        public void Write(string message)

        {

            Console.WriteLine(message);

        }

    }

}

";

 

            #endregion

 

            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);

 

            string assemblyName = Path.GetRandomFileName();

 

            MetadataReference[] referenceArray = new MetadataReference[]

            {

                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),

                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)

            };

 

            CSharpCompilation compilation = CSharpCompilation.Create

            (

                assemblyName,

                syntaxTrees : new[] { syntaxTree },

                references : referenceArray,

                options : new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)

            );

 

            using(MemoryStream stream = new MemoryStream())

            {

                EmitResult result = compilation.Emit(stream);

 

                if(!result.Success)

                {

                    IEnumerable<Diagnostic> diagnosticEnumerable = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError ||

                        diagnostic.Severity == DiagnosticSeverity.Error);

 

                    foreach(Diagnostic diagnostic in diagnosticEnumerable)

                    {

                        Console.Error.WriteLine("{0} : {1}", diagnostic.Id, diagnostic.GetMessage());

                    }

                }

                else

                {

                    stream.Seek(0, SeekOrigin.Begin);

 

                    Assembly assembly = Assembly.Load(stream.ToArray());

 

                    Type type = assembly.GetType("TestProject.Writer");

 

                    object instance = Activator.CreateInstance(type);

 

                    type.InvokeMember

                    (

                        "Write",

                        BindingFlags.Default | BindingFlags.InvokeMethod,

                        null,

                        instance,

                        new object[] { "Hello World" }

                    );

                }

            }

 

            Console.ReadLine();

        }

 

        #endregion

    }

}


----------------------------------------------------------------------------------------------------

※ .NET 4.6 버전 이상에서 지원한다.

Posted by 사용자 icodebroker
TAG

댓글을 달아 주세요