问题描述
在下面的代码中,我需要添加我的程序集,以便脚本可以使用它的类:
In the following code I need to add my assembly so that the script can make use of its classes:
var options = ScriptOptions.Default.AddImports("MyAssembly");
var code = "using MyAssembly.MyNamespace;" +
"public class TestClass {" +
" public int HelloWorld(int num) {" +
" return 5 + num;" +
" }" +
"}";
但是抛出了以下异常:
抛出异常:Microsoft.CodeAnalysis.Scripting.dll 中的Microsoft.CodeAnalysis.Scripting.CompilationErrorException"Microsoft.CodeAnalysis.Scripting.CompilationErrorException:错误 CS0246:找不到类型或命名空间名称MyAssembly"(您是否缺少 using 指令或程序集引用?)
我也在宿主项目中添加了程序集.我也尝试过 此处 中的示例,但他们没有也不能工作.
I added the assembly in the host project too. I've also tried the examples from here but they didn't work either.
添加程序集的正确语法是什么?
What is the correct syntax to add an assembly?
推荐答案
以下代码片段可以解决问题:
The following snippet does the trick:
var path = Assembly.GetAssembly(typeof(MyAssembly.SomeClass)).Location;
var asm = AssemblyMetadata.CreateFromFile(path).GetReference();
var options = ScriptOptions.Default.AddReferences(asm);
以下也有效,它使用 Linq 来获取加载的程序集:
This following works too and it uses Linq to get the loaded assembly:
var asm = AppDomain.CurrentDomain.GetAssemblies()
.SingleOrDefault(assembly => assembly.GetName().Name == "MyAssembly");
然而,这会获取加载的程序集.如果您需要的程序集尚未加载,请使用 Assembly.GetExecutingAssembly().GetReferencedAssemblies()
获取它们.
This however gets the loaded assemblies. If the assembly you need is not already loaded, get them using Assembly.GetExecutingAssembly().GetReferencedAssemblies()
.
这篇关于如何在脚本中添加和使用导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!