用字符串拼接了一个类用CSharpCodeProvider编译时,发生错误。有人用过吗?

解决方案 »

  1.   


    using System;
    using System.CodeDom.Compiler;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Text;
    using Microsoft.CSharp;
    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 IEnumerable<T> GetList<T>(List<T> lists)");
                sb.Append("{");
                sb.Append("return (from item in lists orderby item select item);");
                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);            }
                Console.Read();
            }
        }  
    }
      

  2.   

    本帖最后由 caozhy 于 2012-04-14 22:48:47 编辑
      

  3.   

                cp.ReferencedAssemblies.Add("System.dll");
                cp.ReferencedAssemblies.Add("System.Core.dll");注意把该引用的给引用了.
    用CSharpCodeProvider时,如果出错,记得把需要编译的字符串复制出来,新建一个文件用这个字符串去编译,看看报错,这样查错很快.不然只看出错信息的话你可能很难看明白.
      

  4.   

    另外提一句,有些程序集(哪怕是Framework自带的)不能仅仅通过 System.Core.dll 这种形势来添加,需要程序集的路径.