这是做项目时考虑的多种方案的种,今天上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();
}
}
}