C# 和动态字符串脚本

发布于 2024-11-07 19:43:17 字数 535 浏览 0 评论 0原文

我想要一些关于如何实施我正在从事的项目的关键部分的想法。本质上它是数据映射,我复制字段 x 并将其放入字段 y 中。但是,需要具有在转换期间动态更改(使用字符串操作)该值的能力。

我想要一个文本框,用户可以在其中输入脚本,允许他们使用脚本语言(最好是 VBScript)修改该值。然后,这将允许他们进行简单的操作,例如本示例,这将采用子字符串:

Mid({input_value}, 2, 4)

Where

{input_value} 

将在运行时被实际值替换。

因此,例如,如果“字段 x”的输入是“这是一个测试”,并且他们使用了上面的 start = 2 和 length = 4 的示例,则保存到“字段 y”中的值将是“他的”,

我知道我如何从 C# 作为 scipt 运行 VBScript,这不是问题。但是,是否可以在运行时运行和评估上述脚本并将输出记录回 C# 变量中?

否则,有人对我如何解决这个问题有任何建议吗?

非常感谢

I'd love some ideas about how I should implement a key part of a project I am working on. Essentially it is data mapping, where I copy field x and put it into field y. However, there needs to be some ability to dynamically change (using string manipulation) that value during the transition.

What I would like is a textbox where a user could enter script allowing them to modify that value using a scripting language, ideally VBScript. That would then allow them to do simple manipulations such this example, which would take a substring:

Mid({input_value}, 2, 4)

Where

{input_value} 

Would be replaced by the actual value at runtime.

So, for example, if the input from "field x" was "This is a test" and they used the above example of start = 2 and length = 4, the value saved into "field y" would be "his "

I know how I could run VBScript from C# as a scipt, that's not a problem. However, Is it possible to run and evaluate srcipts such as above at runtime and record the output back into a C# variable?

Otherwise, does anyone have any suggestions about how I could approach this?

Many thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

魔法唧唧 2024-11-14 19:43:17

您可能想要查看基于 DLR 的语言,例如 IronPython 或 IronRuby。两者都允许嵌入,Michael Foord 有一个关于如何将它们嵌入应用程序的教程

如果您使用标准 DLR 接口,我相信您可以嵌入任何语言,包括 DLRBasicASP 经典编译器。 Ben Hall 有一篇关于在生产应用程序中IronRuby 嵌入的文章红门。

我认为您需要查看下面所示的 SetVariable() 和 GetVariable() 方法,以获取从脚本设置和返回数据的示例:

public string evaluate(string x, string code)
{
    scope.SetVariable("x", x);
    scope.SetVariable("button", this.button);

    try
    {
        ScriptSource source = engine.CreateScriptSourceFromString(code,
            SourceCodeKind.Statements);

        source.Execute(scope);
    }
    catch (Exception ex)
    {
        return "Error executing code: " + ex.ToString();
    }

    if (!scope.VariableExists("x"))
    {
        return "x was deleted";
    }
    string result = scope.GetVariable<object>("x").ToString();
    return result;
}

此示例取自 http://www.voidspace.org.uk/ironpython/dlr_hosting.shtml

You might want to look at a DLR-based language like IronPython or IronRuby. Both allow embedding and Michael Foord has a tutorial on how to embed these in an application.

If you use the standard DLR interfaces I believe you can embed any language including DLRBasic and the ASP Classic Compiler. Ben Hall has an article on IronRuby embedding in a production application for Red Gate.

I think you need to review the SetVariable() and GetVariable() methods shown below for an example of setting and return data from scripts:

public string evaluate(string x, string code)
{
    scope.SetVariable("x", x);
    scope.SetVariable("button", this.button);

    try
    {
        ScriptSource source = engine.CreateScriptSourceFromString(code,
            SourceCodeKind.Statements);

        source.Execute(scope);
    }
    catch (Exception ex)
    {
        return "Error executing code: " + ex.ToString();
    }

    if (!scope.VariableExists("x"))
    {
        return "x was deleted";
    }
    string result = scope.GetVariable<object>("x").ToString();
    return result;
}

This example was taken from http://www.voidspace.org.uk/ironpython/dlr_hosting.shtml.

绅士风度i 2024-11-14 19:43:17

这是一个使用表达式运行时编译的工作示例。我借用了这个概念和大部分代码 从这里开始

static void Main(string[] args)
{
    string input = "This is a test";
    string method = "Mid(x, 2, 4)";  // 'x' represents the input value
    string output = Convert(method, input);
    Console.WriteLine("Result: " + output);
    Console.ReadLine();
}

// Convert input using given vbscript logic and return as output string
static string Convert(string vbscript, string input)
{
    var func = GetFunction(vbscript);
    return func(input);
}

// Create a function from a string of vbscript that can be applied
static Func<string, string> GetFunction(string vbscript)
{
    // generate simple code snippet to evaluate expression
    VBCodeProvider prov = new VBCodeProvider();
    CompilerResults results = prov.CompileAssemblyFromSource(
        new CompilerParameters(new[] { "System.Core.dll" }),
        @"
Imports System
Imports System.Linq.Expressions
Imports Microsoft.VisualBasic

Class MyConverter

Public Shared Function Convert() As Expression(Of Func(Of String, String))
    return Function(x) " + vbscript + @"
End Function

End Class
"
        );

    // make sure no errors occurred in the conversion process
    if (results.Errors.Count == 0)
    {
        // retrieve the newly prepared function by executing the code
        var expr = (Expression<Func<string, string>>)
            results.CompiledAssembly.GetType("MyConverter")
                .GetMethod("Convert").Invoke(null, null);
        Func<string, string> func = expr.Compile();

        // create a compiled function ready to apply and return
        return func;
    }
    else
    {
        return null;
    }
}

Here is a working example using runtime compilation of expressions. I borrowed the concept and most of the code from here.

static void Main(string[] args)
{
    string input = "This is a test";
    string method = "Mid(x, 2, 4)";  // 'x' represents the input value
    string output = Convert(method, input);
    Console.WriteLine("Result: " + output);
    Console.ReadLine();
}

// Convert input using given vbscript logic and return as output string
static string Convert(string vbscript, string input)
{
    var func = GetFunction(vbscript);
    return func(input);
}

// Create a function from a string of vbscript that can be applied
static Func<string, string> GetFunction(string vbscript)
{
    // generate simple code snippet to evaluate expression
    VBCodeProvider prov = new VBCodeProvider();
    CompilerResults results = prov.CompileAssemblyFromSource(
        new CompilerParameters(new[] { "System.Core.dll" }),
        @"
Imports System
Imports System.Linq.Expressions
Imports Microsoft.VisualBasic

Class MyConverter

Public Shared Function Convert() As Expression(Of Func(Of String, String))
    return Function(x) " + vbscript + @"
End Function

End Class
"
        );

    // make sure no errors occurred in the conversion process
    if (results.Errors.Count == 0)
    {
        // retrieve the newly prepared function by executing the code
        var expr = (Expression<Func<string, string>>)
            results.CompiledAssembly.GetType("MyConverter")
                .GetMethod("Convert").Invoke(null, null);
        Func<string, string> func = expr.Compile();

        // create a compiled function ready to apply and return
        return func;
    }
    else
    {
        return null;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文