【问题标题】:Referencing current assembly with CompilerParameters使用 CompilerParameters 引用当前程序集
【发布时间】:2012-05-26 07:01:45
【问题描述】:

现在我正在处理一个项目,团队想要一种方法来编写代码并对其进行编辑,而不必重新编译整个项目,因此我决定尝试实现一个脚本引擎。

之前在 C++ 中实现了 Lua,我并不是一个将脚本功能实现到项目中的新手。但是,我们想尝试使用 Microsoft.CSharp 命名空间并结合 C# 中已内置的 System.Reflection 来实现直接的 C#。

听说这件事后,我在文档中翻了一下,我想出了一个几乎可以工作的原型 - 但并不完全。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

namespace Scripting
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("using System;");
            builder.Append("using Scripting;");
            builder.Append("class MyScript : IScript");
            builder.Append("{");
            builder.Append("    string ScriptName");
            builder.Append("    {");
            builder.Append("        get { return \"My Script\"; }");
            builder.Append("    }");

            builder.Append("    public bool Initialize()");
            builder.Append("    {");
            builder.Append("        Console.WriteLine(\"Hello, World!\");");
            builder.Append("        return true;");
            builder.Append("    }");
            builder.Append("}");

            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters param = new CompilerParameters(new string[] { "System.dll", "Scripting.dll" });
            param.GenerateInMemory = true;
            param.GenerateExecutable = true;
            CompilerResults result = provider.CompileAssemblyFromSource(param, builder.ToString());
            if (result.Errors.Count > 0)
            {
                foreach (CompilerError error in result.Errors)
                    Console.WriteLine(error);
                Console.ReadKey();
                return;
            }
        }
    }
}

我目前遇到的问题是我希望能够引用我的接口 - IScript.cs(它位于 Scripting 命名空间内,因此位于当前程序集内) - 以便在编译器中编写和解析的脚本可以访问它。显然,我添加了 Scripting.dll 作为参数,但由于某种原因,它似乎无法访问。我am 在调试中运行它,所以这可能会导致一些主要的面部手掌。做什么?

有没有办法引用当前程序集并将其传递给 CompilerParameters?还是我被彻底搞砸了/我应该依赖为脚本对象/等创建程序集?

【问题讨论】:

  • 你的脚本都在一行上;考虑致电AppendLine()。 (并不是说它会有所作为)

标签: c# reflection scripting


【解决方案1】:

它可能在错误的目录中查找。

传递typeof(Program).Assembly.CodeBase 传递完整路径。

【讨论】:

    【解决方案2】:

    您可以获取可执行文件并将其传递给 CompilerParameters:

           string exeName = Assembly.GetEntryAssembly().Location;      
           param.ReferencedAssemblies.Add(exeName); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多