如何添加对C#脚本的引用 [英] How to Add a Reference to a C# Script
问题描述
我正在使用 CS-Script 库来执行动态代码.与其使用它作为脚本引擎,不如使用它来将功能实时地插入到应用程序中.这是托管代码...
I am using the CS-Script library to execute dynamic code. Rather than using it as a script engine, I want to use it to plug functionality into an application on the fly. Here's the hosting code...
using System;
using CSScriptLibrary;
using System.Reflection;
using System.IO;
namespace CSScriptTester
{
class Program
{
static void Main(string[] args)
{
// http://www.csscript.net/
Console.WriteLine("Running Script.");
CSScript.Evaluator.ReferenceAssembly(Assembly.GetAssembly(typeof(System.Windows.Forms.MessageBox)));
string code = File.ReadAllText("SomeCode/MyScript.cs");
dynamic block = CSScript.Evaluator.LoadCode(code);
block.ExecuteAFunction();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
这是SomeCode/MyScript.cs的内容...
And here's the contents of SomeCode/MyScript.cs...
using System;
using System.Windows.Forms;
namespace CSScriptTester.SomeCode
{
class MyScript
{
public void ExecuteAFunction()
{
MessageBox.Show("Hello, world!");
}
}
}
这很好.在托管代码中,我不希望托管代码负责指定程序集引用.所以我注释掉CSScript.Evaluator.ReferenceAssembly(Assembly.GetAssembly(typeof(System.Windows.Forms.MessageBox)));
并运行它,然后得到错误...
This works fine. In the hosting code, I don't want the hosting code to be responsible for specifying assembly references. So I comment out CSScript.Evaluator.ReferenceAssembly(Assembly.GetAssembly(typeof(System.Windows.Forms.MessageBox)));
and run it and I get the error...
错误CS0234:类型或名称空间名称
Forms' does not exist in the namespace
System.Windows'.您是否缺少装配参考?
error CS0234: The type or namespace name
Forms' does not exist in the namespace
System.Windows'. Are you missing an assembly reference?
我知道是否使用命令行工具执行此操作,可以将其添加到脚本顶部以添加引用...
I know if I were executing this using the command line tools I could add this to the top of the script to add the reference...
//css_reference System.Windows.Forms.dll
但是,在.NET应用程序上下文中执行该命令时,似乎忽略了这一点.我该如何正确解析引用?
But that seems to be ignored when executing it in the context of a .NET Application. How can I get it to resolve the references properly?
推荐答案
弄清楚了.
string code = File.ReadAllText("SomeCode/MyScript.cs");
CSScript.Evaluator.ReferenceAssembliesFromCode(code);
dynamic block = CSScript.Evaluator.LoadCode(code);
block.ExecuteAFunction();
我很惊讶它没有自动执行此操作.
I'm surprised that it doesn't automatically do this.
这篇关于如何添加对C#脚本的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!