첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

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()
        {
            Console.Title = "CSharpCompilation 클래스 : 런타임에서 C# 코드를 동적으로 컴파일하기";

            #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 버전 이상에서 지원한다.

728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요