使用C#作为C#应用程序的脚本语言

Rag*_*mar 6 c# scripting

我开发了一个应用程序,它使用c#脚本文件进行某些配置和设置.脚本文件包含各种用户生成的对象以及这些对象上的某些功能.目前,用户必须使用第三方编辑器生成.cs文件,并提供我的程序的路径以使用它.这种方法的缺点是用户在编辑脚本文件时没有自动完成和智能感知支持的灵活性.

我想将脚本编辑部分嵌入到我的应用程序中.我可以使用富文本编辑器来做到这一点.但编码自动完成部分是一个巨大的痛苦.有什么方法可以为用户提供程序内编辑器,也可以自动完成....

用于在程序中动态编译脚本的代码.

public String Compile(String inputfilepath)
    {

        CompilerResults res = null;
        CSharpCodeProvider provider = new CSharpCodeProvider();
        String errors = "";

        if (provider != null)
        {
            try
            {
                Assembly asb = Assembly.Load("BHEL.PUMPSDAS.Datatypes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=81d3de1e03a5907d"); 
                CompilerParameters options = new CompilerParameters();
                options.GenerateExecutable = false;
                options.OutputAssembly = String.Format(outFileDir + oName);
                options.GenerateInMemory = false;
                options.TreatWarningsAsErrors = false;
                options.ReferencedAssemblies.Add("System.dll");
                options.ReferencedAssemblies.Add("System.Core.dll");
                options.ReferencedAssemblies.Add("System.Xml.dll");
                options.ReferencedAssemblies.Add("System.Xml.dll");
                options.ReferencedAssemblies.Add(asb.Location);
                res = provider.CompileAssemblyFromFile(options, inputfilepath);
                errors = "";
                if (res.Errors.HasErrors)
                {
                    for (int i = 0; i < res.Errors.Count; i++)
                    {
                        errors += "\n " + i + ". " + res.Errors[i].ErrorText;
                    }
                }
            }

            catch (Exception e)
            {
                throw (new Exception("Compilation Failed with Exception!\n" + e.Message +
                    "\n Compilation errors : \n" + errors + "\n"));
            }

        }
        return errors;
    }
Run Code Online (Sandbox Code Playgroud)

Zen*_*xer 2

特别是对于自动完成,您将需要使用两个系统:解析器和反射。

从理论上讲,解析器是一个非常简单的概念,但我确信,为具有如此多语法糖和如此多上下文相关关键字的语言(如 C#)编写该语言并不容易。

由于 .NET 本质上是反射性的,并且提供了反射框架,因此这部分也不应该是非常痛苦的。反射允许您将包含已编译程序集的面向对象元素以及程序集本身作为对象进行操作。Method例如,方法可以是对象。您可以通过检查类的成员来了解这个系统Type,这提供了一个基本的反思起点。另一个有用的起点是AssemblyMSDN和往常一样,拥有大量结构化格式的“官方”信息。