pro*_*eek 1 c# ironpython dynamic-language-runtime
我有以下IronPython代码.
class Hello:
def __init__(self):
pass
def add(self, x, y):
return (x+y)
Run Code Online (Sandbox Code Playgroud)
我可以使用以下C#代码来使用IronPython代码.
static void Main()
{
string source = GetSourceCode("ipyth.py");
Engine engine = new Engine(source);
ObjectOperations ops = engine._engine.Operations;
bool result = engine.Execute();
if (!result)
{
Console.WriteLine("Executing Python code failed!");
}
else
{
object klass = engine._scope.GetVariable("Hello");
object instance = ops.Invoke(klass);
object method = ops.GetMember(instance, "add");
int res = (int) ops.Invoke(method, 10, 20);
Console.WriteLine(res);
}
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
我可以使用动态DLR使这段代码更简单吗?
该IronPython的行动中书有在<15.4.4动态对象进行交互的未来>关于它的简单的解释,但我无法找到一些例子.
我附上程序的源/批处理文件. Program.cs runme.bat
是的,动态可以使您的代码更简单
var source =
@"
class Hello:
def __init__(self):
pass
def add(self, x, y):
return (x+y)
";
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
var ops = engine.Operations;
engine.Execute(source, scope);
var pythonType = scope.GetVariable("Hello");
dynamic instance = ops.CreateInstance(pythonType);
var value = instance.add(10, 20);
Console.WriteLine(value);
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2575 次 |
| 最近记录: |