gpt4 book ai didi

c# - CodeDom 编译器 : Type or namespace 'Foo' does not exist in the namespace 'System'

转载 作者:行者123 更新时间:2023-11-30 22:37:34 26 4
gpt4 key购买 nike

我正在编写一个生成 C# 代码的工具,并正在编写单元测试来配合它。

我想做的测试之一是运行该工具并编译结果,这样我就可以用反射检查程序集。但是,我在这样做时遇到了麻烦。我当前的代码如下所示:

var args = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
var compiler = new CSharpCodeProvider();

var parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.ReferencedAssemblies.Add("System.Data.dll");
parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
parameters.ReferencedAssemblies.Add("System.Xml.dll");
parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");

var results = compiler.CompileAssemblyFromFile(new CompilerParameters(), Directory.GetFiles("Model\\Editable").Concat(Directory.GetFiles("Model\\NotEditable")).ToArray());

if (results.Errors.Count > 0) {
StringBuilder sb = new StringBuilder();

foreach (CompilerError err in results.Errors) {
sb.AppendLine(err.FileName + "(" + err.Line + ":" + err.Column + "): " + err.ErrorText);
}

throw new Exception(sb.ToString());
}

异常通常不是测试的一部分,只是让我可以查看吐出的错误。可悲的是,我遇到的错误是:

c:\<redacted>\bin\Debug\Model\NotEditable\Computer.cs(5:14): The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)
c:\<redacted>\bin\Debug\Model\NotEditable\Computer.cs(6:14): The type or namespace name 'Data' does not exist in the namespace 'System' (are you missing an assembly reference?)
c:\<redacted>\bin\Debug\Model\NotEditable\Computer.cs(7:14): The type or namespace name 'Data' does not exist in the namespace 'System' (are you missing an assembly reference?)
c:\<redacted>\bin\Debug\Model\NotEditable\Computer.cs(8:14): The type or namespace name 'ComponentModel' does not exist in the namespace 'System' (are you missing an assembly reference?)

我是否正确添加了这些引用,还是我做错了什么?

最佳答案

看起来您应该将参数传递给 CompileAssemblyFromFile,而不是 CompilerParameters 的新实例。

var results = compiler.CompileAssemblyFromFile(parameters, Directory.GetFiles("Model\\Editable").Concat(Directory.GetFiles("Model\\NotEditable")).ToArray());

关于c# - CodeDom 编译器 : Type or namespace 'Foo' does not exist in the namespace 'System' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6459274/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com