CSharpCodeProvider编译器无法识别脚本中的父类

问题描述 投票:0回答:1

我已经建立了一个简单的控制台应用程序

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:评论建议

我在解决方案中创建了新的库项目,在其中添加了空的public class BaseClass,在Program.cs中添加了对该项目的引用。

enter image description here这就是我在Program.cs

中所做的更改
        var compileOptions = new CompilerParameters();
        var assembliesPath = AppDomain.CurrentDomain.BaseDirectory;
        compileOptions.ReferencedAssemblies.Add(assembliesPath + "TestLibrary.dll");
        compileOptions.GenerateInMemory = true;

我已经重建了两个项目,但仍然遇到相同的错误。

c# inheritance csharpcodeprovider
1个回答
0
投票

解决方案是我的问题中的“编辑1:评论建议”与我的最后评论“我忘记添加'using TestLibrary;'在我脚本的顶部。”,看起来像这样

        var scriptText = @"
            using TestLibrary; // <- this line here
            namespace TestingInConsole
            {
                public class Test : BaseClass
                {
                }
            }";
© www.soinside.com 2019 - 2024. All rights reserved.