c# – CodeDomProvider代码生成因某些Linq语法而失败

我正在使用CodeDomProvider to compile some Linq code并动态执行查询.但是,我遇到了一个非常奇怪的问题.

如果我生成的代码中的Linq查询看起来像这样,一切正常:

namespace Dynamic
{
    using System.Linq;
    using System.Collections.Generic;

    public static class Query
    {
        public static int GetRecords()
        {
            MyData.Data.DataMart container = new MyData.Data.DataMart();
            return (container.EventDetails).Count();
        }
    }
}

这编译并运行得很好.但是,如果我将linq查询更改为以下内容,则无法编译:

return (from e in container.EventDetails select e).Count();

如果我把它作为静态代码,它工作正常,但如果我尝试使用CodeDomProvider编译它失败(我没有找到任何好的方法来获取错误消息为什么它失败).我想使用from-in-select样式的语法,因为这将使我更容易生成linq查询,但我无法弄清楚它们为什么不编译.

您可以在本文顶部的链接中看到我用来编译此代码段的一些代码.

谢谢!

编辑:从我链接到的帖子中复制代码:

CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters cp = new CompilerParameters();
cp.GenerateInMemory = true;
cp.ReferencedAssemblies.Add("mscorlib.dll");
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Core.dll");
cp.ReferencedAssemblies.Add("System.Data.Linq.dll");
cp.ReferencedAssemblies.Add("System.Data.Entity.dll");
cp.ReferencedAssemblies.Add("MyApp.Data.dll");

var results = provider.CompileAssemblyFromSource(cp, source);
var assm = results.CompiledAssembly; 

Edit2:就异常而言,我在第二行到最后一行代码上得到一个异常(var results = …). BadImageFormatException是一个例外:

Could not load file or assembly ‘0 bytes loaded from System,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’ or
one of its dependencies. An attempt was made to load a program with an
incorrect format

解决方法:

这似乎对我有用:

    static void Main(string[] args)
    {
        string sourceCode = @"namespace Dynamic {
using System.Linq;
using System.Collections.Generic;

public static class Query
{
    public static int GetRecords()
    {
        MyApp.Data.DataMart container = new MyApp.Data.DataMart();
        //return (container.EventDetails).Count();
        return (from e in container.EventDetails select e).Count();
    }
} }";

        string sDynamDll = "Dynamic.dll";
        string sDynamClass = "Query";
        string sDynamMethod = "GetRecords";

        System.CodeDom.Compiler.CompilerParameters cp = new CompilerParameters();
        cp.GenerateExecutable = false;
        cp.GenerateInMemory = true;
        cp.OutputAssembly = sDynamDll;
        cp.ReferencedAssemblies.Add("mscorlib.dll");
        cp.ReferencedAssemblies.Add("System.dll");
        cp.ReferencedAssemblies.Add("System.Core.dll");
        cp.ReferencedAssemblies.Add("System.Data.Linq.dll");
        cp.ReferencedAssemblies.Add("System.Data.Entity.dll");
        cp.ReferencedAssemblies.Add("MyApp.Data.dll");

        var providerOptions = new Dictionary<string, string>();
        providerOptions.Add("CompilerVersion", "v4.0");
        CodeDomProvider compiler = CodeDomProvider.CreateProvider("C#", providerOptions);
        CompilerResults cr = compiler.CompileAssemblyFromSource(cp, sourceCode);
        if (cr.Errors.HasErrors)
        {
            StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
            foreach (CompilerError error in cr.Errors)
            {
                errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText);
            }
        }

        // verify assembly
        Assembly theDllAssembly = null;
        if (cp.GenerateInMemory)
            theDllAssembly = cr.CompiledAssembly;
        else
            theDllAssembly = Assembly.LoadFrom(sDynamDll);

        Type theClassType = theDllAssembly.GetType(sDynamClass);

        foreach (Type type in theDllAssembly.GetTypes())
        {
            if (type.IsClass == true)
            {
                if (type.FullName.EndsWith("." + sDynamClass))
                {
                    theClassType = type;
                    break;
                }
            }
        }

        // invoke the method
        if (theClassType != null)
        {
            object[] method_args = new object[] { };

            Object rslt = theClassType.InvokeMember(
                sDynamMethod,
              BindingFlags.Default | BindingFlags.InvokeMethod,
                   null,
                   null, // for static class
                   method_args);

            Console.WriteLine("Results are: " + rslt.ToString());
        }

        Console.ReadKey();
    }
上一篇:使用C#在运行时编译java代码


下一篇:java – 如何在定位较旧的JDK版本时避免使用NoClassDefFoundErrors和NoSuchMethodErrors?