gpt4 book ai didi

c# - 如何将重载方法暴露给嵌入式 IronPython 解释器?

转载 作者:行者123 更新时间:2023-11-30 22:46:34 25 4
gpt4 key购买 nike

我在 C# 应用程序中嵌入了一个 IronPython 引擎。我想向解释器公开一些自定义命令(方法)。我该怎么做?

目前,我有这样的东西:

public delegate void MyMethodDel(string printText);

Main(string[] args)
{
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();

MyMethodDel del = new MyMethodDel(MyPrintMethod);
scope.SetVariable("myprintcommand", del);

while(true)
{
Console.Write(">>>");
string line = Console.ReadLine();

ScriptSource script = engine.CreateScriptSourceFromString(line, SourceCodeKind.SingleStatement);
CompiledCode code = script.Compile();
script.Execute(scope);
}
}

void MyPrintMethod(string text)
{
Console.WriteLine(text);
}

我可以这样使用:

>>>myprintcommand("Hello World!")
Hello World!
>>>

这很好用。我想知道,这是否是实现我想要实现的目标的正确方法/最佳实践?

如何公开相同方法的重载。例如,如果我想公开一个像 myprintcommand(string format, object[] args) 这样的方法。

按照我目前的做法,键“myprintcommand”只能映射到一个代表。因此,如果我想将重载的“myprintcommand”暴露给解释器,我将不得不更改命令/方法的名称。有没有其他方法可以实现我想要的?

最佳答案

您可能必须为此编写自己的逻辑。例如:

public delegate void MyMethodDel(params object[] args);

void MyPrintMethod(params object[] args)
{
switch (args.Length)
{
case 1:
Console.WriteLine((string)args[0]);
break;
...
default:
throw new InvalidArgumentCountException();
}
}

这可能有效也可能无效;我不确定他们是如何处理“params”属性的。

关于c# - 如何将重载方法暴露给嵌入式 IronPython 解释器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2584251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com