如何让程序集在运行时生成以使用项目依赖项? C#

How to get Assemblies Generated at Runtime to use Project Dependencies? C#

是否可以允许动态生成的程序集访问生成新程序集的项目中存在的依赖项?我正在使用 Unity 和 C#,我添加了一个程序集,其中包含存在于它现在所属的项目中的依赖项,但我收到此错误:FileNotFoundException:无法加载文件或程序集 'ModAssembly000.dll' 或其依赖项之一.我收到此错误是因为我尝试将 'using UnityEngine' 放在脚本的顶部。这是获取新程序集并调用方法的项目中已经存在的代码:

        CompilerParameters parameters = new CompilerParameters();
    parameters.GenerateExecutable = false;
    parameters.GenerateInMemory = true;
    parameters.OutputAssembly = generatedName;
    CompilerResults r = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromFile(parameters, filePath);
    r.CompiledAssembly.GetType("ModData").GetMethod("Run").Invoke(null, BindingFlags.Static, null, null, null);

这是动态创建的程序集的来源:

using UnityEngine;

public class ModData {
    public static string modName = "Super kool mod";
    public static string modVersion = "1.2.1";

    public static void Run() {
        Debug.Log("it worked :D");
    }
}

UnityEngine(因此,Debug.Log)存在于生成此程序集的代码中。有没有办法让新创建的程序集使用存在于其上方的 UnityEngine,以便我可以允许新代码在其上方的项目中执行任何操作?我知道 ModAssembly000.dll 存在,因为如果我删除 'using UnityEngine' 行,那么我可以毫无问题地访问动态程序集的静态字符串字段。

我的猜测是您需要将 Unity 添加到引用程序集的列表中:

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