在动态编译的代码中缺少程序集引用

时间:2010-10-31 13:32:16

标签: c#

感谢关于此问题的第一篇帖子的消息。我会做一个转贴,并试着这次更清楚。我想这可能是一个微不足道的问题,但我真的很困难,需要一些帮助。这是我第一次在这里发帖。

using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
namespace DynamicCode
{
public class DynaCore
{
string WorkingCode = 
    "using System;"+
    "using System.Collections.Generic;"+
    "namespace DynaCore"+
    "{"+
    "   public class DynaCore"+
    "   {"+
    "       static public string DynamicResult()"+
    "       {"+
    "           return \"I'm compiled\";"+
    "       }"+
    "   }"+
    "}";


string PredicateTemplCode = 
    "using System;"+
    "using System.Linq;"+
    "using System.Collections.Generic;"+
    "namespace DynaCore"+
    "{"+
    "   public class DynaCore"+
    "   {"+
    "       static public Func<{1}, bool> DynamicResult()"+
    "       {"+
    "           return new Func<{1}, bool>({2});"+
    "       }"+
    "   }"+
    "}";

public DynaCore()
{
    string compiledString = WorkingCompilation(WorkingCode);
    Func<bool, bool> compiladePredicate = NotWorkingCompilation<bool>(PredicateTemplCode, "(o)=> true");
}

string WorkingCompilation(string code)
{
    var cParams = new CompilerParameters();
    cParams.GenerateInMemory = true;
    cParams.TreatWarningsAsErrors = false;
    cParams.GenerateExecutable = false;
    cParams.CompilerOptions = "/optimize /target:library";

    var curAss = Assembly.GetExecutingAssembly();

    cParams.ReferencedAssemblies.Add("System.dll");
    cParams.ReferencedAssemblies.Add("mscorlib.dll");
    cParams.ReferencedAssemblies.Add("System.dll");
    cParams.ReferencedAssemblies.Add("System.Data.dll");
    cParams.ReferencedAssemblies.Add(curAss.Location);

    var provider = new CSharpCodeProvider();

    var compalerResult = provider.CompileAssemblyFromSource(cParams, code);

    if (compalerResult.Errors.HasErrors)
    {
        var complieError = "";
        foreach (CompilerError ce in compalerResult.Errors)
            complieError += ce + " ";

        throw new Exception(complieError.Trim());
    }

    Module module = compalerResult.CompiledAssembly.GetModules()[0];
    Type mt = null;
    MethodInfo methInfo = null;

    return (string)module.GetType("DynaCore.DynaCore").GetMethod("DynamicResult").Invoke(null, null);
}


Func<T, bool> NotWorkingCompilation<T>(string code, string predicateString)
{
    var cParams = new CompilerParameters();
    cParams.GenerateInMemory = true;
    cParams.TreatWarningsAsErrors = false;
    cParams.GenerateExecutable = false;
    cParams.CompilerOptions = "/optimize /target:library";

    var curAss = Assembly.GetExecutingAssembly();

    cParams.ReferencedAssemblies.Add("System.dll");
    cParams.ReferencedAssemblies.Add("mscorlib.dll");
    cParams.ReferencedAssemblies.Add("System.dll");
    cParams.ReferencedAssemblies.Add("System.Data.dll");
    cParams.ReferencedAssemblies.Add("System.Core.dll");
    cParams.ReferencedAssemblies.Add(curAss.Location);

    var provider = new CSharpCodeProvider();

    var codeToRun = code.Replace("{1}", typeof(T).Name).Replace("{2}", predicateString);
    var compalerResult = provider.CompileAssemblyFromSource(cParams, codeToRun);

    if (compalerResult.Errors.HasErrors)
    {
        var complieError = "";
        foreach (CompilerError ce in compalerResult.Errors)
            complieError += ce + " ";

        throw new Exception(complieError.Trim());
    }

    Module module = compalerResult.CompiledAssembly.GetModules()[0];
    Type mt = null;
    MethodInfo methInfo = null;

    return (Func<T, bool>)module.GetType("DynaCore.DynaCore").GetMethod("DynamicResult").Invoke(null, null);
}
}
}

问题是当我在 ReferencedAssemblies.Add(“System.Core.dll”)中引用 System.Core.dll 时,它会给我一个编译错误:

错误CS0006:找不到元数据文件'System.Core.dll'

我正在使用v3.5和VS 2008.

5 个答案:

答案 0 :(得分:10)

感谢所有答案!

事实证明,CSharpCodeProvider默认为2.0版,不支持泛型或linq。以下解决了问题:

var provider = new CSharpCodeProvider(
    new Dictionary<String, String>{{ "CompilerVersion","v3.5" }});

答案 1 :(得分:6)

我以为我会更新这个帖子,因为它从来没有得到正确回答。我刚刚遇到了同样的问题(CS0006),不得不包含一个WPF目录中的WPF库,最后用以下内容修复它:

            string ver = string.Format("{0}.{1}.{2}", Environment.Version.Major, Environment.Version.MajorRevision, Environment.Version.Build);
            string exWpfDir = string.Format(@"C:\WINDOWS\Microsoft.NET\Framework\v{0}\WPF", ver);
            string exDir = string.Format(@"C:\WINDOWS\Microsoft.NET\Framework\v{0}", ver);

            CSharpCodeProvider provider = new CSharpCodeProvider();
            ICodeCompiler compiler = provider.CreateCompiler();
            CompilerParameters compilerparams = new CompilerParameters();
            compilerparams.GenerateExecutable = false;
            compilerparams.GenerateInMemory = true;
            compilerparams.IncludeDebugInformation = false;
            compilerparams.TreatWarningsAsErrors = false;
            compilerparams.CompilerOptions = string.Format("/lib:{0}", exWpfDir);
            compilerparams.CompilerOptions = string.Format("/lib:{0}", exDir);

答案 2 :(得分:2)

另一个问题可能是System.Core.dll实际上位于与其他dll不同的位置。

在我的计算机上,System.Core.dll位于%ProgramFiles%\ Reference Assemblies \ Microsoft \ Framework \ v3.5 \ System.Core.dll中,而其他dll位于GAC中。

答案 3 :(得分:1)

有时您需要将引用的程序集添加到CSharpCodeProvider参数。

parameters.ReferencedAssemblies.Add("System.dll");

希望这有帮助。

答案 4 :(得分:0)

结果代码

using System;
using System.Linq;
using System.Collections.Generic;
namespace DynaCore
{
    public class DynaCore
    {
        static public Func<Boolean, bool> Main()
        {
            Func<Boolean, bool> retur = (o) => true;
        }
    }
}
粘贴到新文件时,

不会自行编译。第一个编译错误是

  

'DynaCore.DynaCore.Main()':并非所有代码路径都返回值

首先,您需要生成粘贴到空.cs文件时编译的代码。

第一个显而易见的事情是将func语句修复为类似

的内容
return new Func<Boolean, bool>(o => true);

修改
并且不要调用方法Main