关于动态执行LAMBDA表达示

这是做项目时考虑的多种方案的种,今天上csdn看到有个兄弟留言.以前做过测试的程序发上来让大家看看. 代码没整理.

using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.CSharp;
using System.Reflection;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append("using System.Linq;");
            sb.Append("using System;");
            sb.Append("using System.Collections.Generic;");
            sb.Append("namespace Test");
            sb.Append("{");
            sb.Append("public class Class1");
            sb.Append("{");
            sb.Append("public List<T> GetList<T>(List<T> lists)");
            sb.Append("{");
            sb.Append("return (from item in lists orderby item select item).ToList();");
            sb.Append("}");
            sb.Append("}");
            sb.Append("}");

            CSharpCodeProvider cs = new CSharpCodeProvider();

            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = false;
            cp.OutputAssembly = "Test.dll";
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Core.dll");

            CompilerResults cr = cs.CompileAssemblyFromSource(cp, sb.ToString());

            if (cr.Errors.Count > 0)
            {
                foreach (var item in cr.Errors)
                    Console.WriteLine(item);

            }

           Assembly ass  = Assembly.LoadFrom("./Test.dll");

           Type type = ass.GetType("Test.Class1");

           MethodInfo m = type.GetMethod("GetList");

            object obj = ass.CreateInstance(type.FullName);

           List<int> items = new List<int>() { 3, 1, 2 };

           MethodInfo mm = m.MakeGenericMethod(typeof(int));

           object[] a = { items };

           var o= mm.Invoke(obj, a) as IList<int>;

           foreach (var ii in o)
               Console.WriteLine(ii);    

          


            Console.Read();
        }
    }


}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值