CodeDom编译器:类型或命名空间';Foo';不存在于命名空间';系统';
本文关键字:命名空间 不存在 Foo 系统 CodeDom 类型 编译器 | 更新日期: 2023-09-27 18:00:04
我正在编写一个生成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());
在示例代码中,您没有使用初始化的CompilerParameters。
var results = compiler.CompileAssemblyFromFile(parameters, Directory.GetFiles("Model''Editable").Concat(Directory.GetFiles("Model''NotEditable")).ToArray());