public static DynamicMethod CopyToDynamicMethod([NotNull] MethodDefinition method)
        {
            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }

            var dynamicMethod = new DynamicMethod(
                method.Name,
                GetRuntimeType(method.ReturnType),
                method.Parameters.Select(param => GetRuntimeType(param.ParameterType)).ToArray(),
                true);

            dynamicMethod.InitLocals = method.Body.InitLocals;

            var ilGenerator = dynamicMethod.GetILGenerator();

            var copier = new ILCopier(ilGenerator);

            copier.CopyFrom(method);

            return(dynamicMethod);
        }
        public Delegate Compile([NotNull] Type delegateType)
        {
            var syntaxTree = CreateSyntaxTree();

            var references = _referenceLocations
                             .Distinct()
                             .Where(File.Exists)
                             .Select(location => MetadataReference.CreateFromFile(location))
                             .ToList();

            var compilation = CSharpCompilation.Create(ExpressionCompilerAssemblyName)
                              .WithReferences(references)
                              .WithOptions(_compilerOptions)
                              .AddSyntaxTrees(syntaxTree);

            using (var memoryStream = new MemoryStream())
            {
                var emitResult = compilation.Emit(memoryStream);

                if (!emitResult.Success)
                {
                    throw new CompilationErrorException(emitResult, syntaxTree);
                }

                memoryStream.Position = 0;

                var module = ModuleDefinition.ReadModule(memoryStream);

                var method = module.Types
                             .SelectMany(item => item.Methods)
                             .Single(item => item.Name == MethodName);

                var dynamicMethod = ILCopier.CopyToDynamicMethod(method);
                return(dynamicMethod.CreateDelegate(delegateType));
            }
        }