C# CSharpCodeProvider编译器无法识别脚本中的父类
我已经设置了一个简单的控制台应用程序 在C# CSharpCodeProvider编译器无法识别脚本中的父类,c#,inheritance,csharpcodeprovider,C#,Inheritance,Csharpcodeprovider,我已经设置了一个简单的控制台应用程序 在Program.cs中,我试图在继承基类的同时编译脚本 using Microsoft.CSharp; using System; using System.CodeDom.Compiler; using System.Data; namespace TestingInConsole { public class BaseClass { } class Program { static void Main(str
Program.cs
中,我试图在继承基类的同时编译脚本
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Data;
namespace TestingInConsole
{
public class BaseClass { }
class Program
{
static void Main(string[] args)
{
var scriptText = @"
namespace TestingInConsole
{
public class Test : BaseClass
{
}
}";
var compileOptions = new CompilerParameters();
compileOptions.GenerateInMemory = true;
var compiler = new CSharpCodeProvider();
var compileResult = compiler.CompileAssemblyFromSource(compileOptions, scriptText);
if (compileResult.Errors.Count > 0)
throw new Exception($"Error in script: {compileResult.Errors[0].ErrorText}\nLine: {compileResult.Errors[0].Line}");
var assembly = compileResult.CompiledAssembly;
dynamic script = assembly.CreateInstance($"TestingInConsole.Test");
// TODO: add Run() function to Test class
DataSet dataSetResult = script.Run();
}
}
}
但是我得到了错误
System.Exception:'脚本中的错误:找不到类型或命名空间名称'BaseClass'(是否缺少using指令或程序集引用?)行:4'
行后:if(compileResult.Errors.Count>0)
问题 像这样的CSharpCodeProvider脚本是否可以继承基类 或者我应该在
Program.cs
中创建新函数来检查脚本实例是否具有正确的函数(在其他情况下,我会将其放入基类中)?编辑1:来自评论的建议 我在我的解决方案中创建了新的库项目,向其中添加了空的
公共类基类
,并在Program.cs
中添加了对它的引用
这就是我在
Program.cs
var compileOptions = new CompilerParameters();
var assembliesPath = AppDomain.CurrentDomain.BaseDirectory;
compileOptions.ReferencedAssemblies.Add(assembliesPath + "TestLibrary.dll");
compileOptions.GenerateInMemory = true;
我已经重建了这两个项目,但仍然得到了相同的错误。解决方案是我问题中的“编辑1:来自评论的建议”,再加上我最后的评论“我忘了在脚本顶部添加‘使用TestLibrary;’”,看起来是这样的
var scriptText = @"
using TestLibrary; // <- this line here
namespace TestingInConsole
{
public class Test : BaseClass
{
}
}";
var scriptText=@”
using TestLibrary;//我认为MS有一些关于将程序集动态加载到另一个程序集的帮助页面——这应该会告诉您如何执行。您需要一个我期望的using语句。然后是@Hogan所说的。将基本脚本添加到新的类库中,并在执行脚本时将类库添加为引用。这不是“JIT”,JIT是运行时将IL字节码转换为CPU指令时执行的操作。您必须执行与在IDE项目中相同的操作,向引用节点添加条目。是的,添加对您自己的.exe文件的引用很好。我将再次强调,创建DLL是没有必要的。但是现在您已经这样做了,我们无法再查看DLL是否存在于正确的目录中(msbuild不再有帮助),以及您是否使用了正确的命名空间名称。如果错误完全相同,则可能是名称空间名称。