.NET 即时编译

RuiJi.Net 在地址处理上使用即时编译

我们在制作抓取软件的过程中,发现某些新闻源地址是动态变化的,例如

http://www.xxx.com/2018/05/01/roll.html

某些网站的滚动新闻页面地址会根据当前日期发生变化

所以RuiJi.Net内置了地址生成函数

例如:now(format)

在录入新闻源时,使用方式如下

http://www.xxx.com/{# now(“yyyy/MM/dd”) #}/roll.html

同时计划函数可以自行扩展,使用如下的定义方式

函数名: xxx

参数:xxx

代码 :

result = Datetime.Now.ToString({0})

描述: xxxx

即时编译器代码如下

public class JITCompile
    {
        private static string GenerateCode(string code)
        {
            return @"
            using System;
            using System.ComponentModel;
            using System.Text;
            using System.Text.RegularExpressions;
            using System.Collections;
            using System.Collections.Generic;
            using System.Reflection;

            sealed class RuiJiCompile
            {
                public static object v;
                
                public static void Main()
                {
                    
                }

                public static object Exec()
                {
                    object result;
                    " + code + @"
                    return result;
                }
            }";
        }

        private static CompilerResults Compile(string codes)
        {
            var compiler = new CSharpCodeProvider();
            var parameters = new CompilerParameters();
            parameters.WarningLevel = 4;
            parameters.GenerateInMemory = true;
            parameters.ReferencedAssemblies.Add("System.dll");

            return compiler.CompileAssemblyFromSource(parameters, codes);
        }

        public static string GetResult(string code)
        {
            code = GenerateCode(code);
            var result = Compile(code);

            if(result.Errors.HasErrors)
            {
                var es = "";
                foreach (CompilerError er in result.Errors)
                {
                    es += er.ErrorText;
                }

                return es;
            }

            Type type = result.CompiledAssembly.GetType("RuiJiCompile");
            return type.GetMethod("Exec").Invoke(null, new string[] { }).ToString();
        }
    }

using 及 引用库 在将来也计划可以自由选择

猜你喜欢

转载自blog.csdn.net/weixin_42581666/article/details/106169179