Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

c# - How to add and use an import in a script?

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;" +
           "  }" +
           "}";

But the following exception is thrown:

Exception thrown: 'Microsoft.CodeAnalysis.Scripting.CompilationErrorException' in Microsoft.CodeAnalysis.Scripting.dll Microsoft.CodeAnalysis.Scripting.CompilationErrorException: error CS0246: The type or namespace name 'MyAssembly' could not be found (are you missing a using directive or an assembly reference?)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

This following works too and it uses Linq to get the loaded assembly:

var asm = AppDomain.CurrentDomain.GetAssemblies()
    .SingleOrDefault(assembly => assembly.GetName().Name == "MyAssembly");

This however gets the loaded assemblies. If the assembly you need is not already loaded, get them using Assembly.GetExecutingAssembly().GetReferencedAssemblies().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...