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

namespace DynamicCompiler
{
    public class Compiler
    {
        /// <summary>
        /// 编译
        /// </summary>
        /// <param name="codeString">需要编译的代码</param>
        /// <param name="outputAssembly">输出程序集位置</param>
        public void Compile(string codeString, string outputAssembly)
        {
            CompilerParameters compilerParams = new CompilerParameters();
            ///编译器选项设置
            compilerParams.CompilerOptions = "/target:library /optimize";

            compilerParams.OutputAssembly = outputAssembly;
            ///生成调试信息
            compilerParams.IncludeDebugInformation = false;

            ///添加相关的引用
            foreach (var item in ReferencedAssemblies)
            {
                compilerParams.ReferencedAssemblies.Add(item);
            }

            CSharpCodeProvider provider = new CSharpCodeProvider();

            ///编译
            CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, codeString);
            if (results.Errors.HasErrors)
            {
                StringBuilder errors = new StringBuilder();
                foreach (CompilerError item in results.Errors)
                {
                    errors.AppendLine(item.ToString());
                }
                throw new Exception(errors.ToString());
            }
            ///创建程序集
            Assembly asm = results.CompiledAssembly;


        }
        private StringCollection ReferencedAssemblies
        { get; set; }
        public Compiler(StringCollection referencedAssemblies)
        {
            ReferencedAssemblies = referencedAssemblies;
            ReferencedAssemblies.Add("mscorlib.dll");
            ReferencedAssemblies.Add("System.dll");
        }
        public Compiler()
            : this(new StringCollection())
        { }
    }
}
