我使用书中的代码在 mono 2.8 上测试了 IronPython Professional IronPython p.315 list 15-3。
using System;
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting.Hosting;
namespace Method2
{
class Program
{
static void Main(string[] args)
{
// Obtain the runtime.
var IPY = Python.CreateRuntime();
// Create a dynamic object containing the script.
dynamic TestPy = IPY.UseFile("TestClass.py");
// Execute the __test__() method.
TestPy.__test__();
}
}
}
我发现它编译正常,并且在 Windows 7 上运行没有问题,而 mono 2.8 却给出了以下错误消息。
Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: `Microsoft.Scripting.Hosting.ScriptScope' does not contain a definition for `__test__' at (wrapper dynamic-method) object.CallSite.Target (System.Runtime.CompilerServices.Closure,System.Runtime.CompilerServices.CallSite,object) at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid1 (System.Runtime.CompilerServices.CallSite,object) at Method2.Program.Main (string[])
I thought Mono 2.8 supports C# 4.0 which has the dynamic keyword, but I see that the 'dynamic' keyword is not fully supported with mono.
Is this a bug of Mono 2.8?
ADDED
This is the python script.
# The class you want to access externally.
class DoCalculations():
# A method within the class that adds two numbers.
def DoAdd(self, First, Second):
# Provide a result.
return First + Second
# A test suite in IronPython.
def __test__():
# Create the object.
MyCalc = DoCalculations()
# Perform the test.
print MyCalc.DoAdd(5, 10)
# Pause after the test session.
raw_input('\nPress any key to continue...')
这是我使用的命令
dmcs Program.cs /r:System.Core /r:IronPython.dll /r:IronPython.Modules.dll /r:Microsoft.Dynamic.dll /r:Microsoft.Scripting.dll /r:Microsoft.CSharp.dll
它编译得很好,但当我运行执行二进制文件时它仍然中断。我需要将所有 dll 放在执行二进制文件所在的同一目录中吗?
最佳答案
您收到 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
的事实意味着动态关键字起作用了。您遇到的问题是 IPY.UseFile("TestClass.py");返回一个看不到您的测试方法的 ScriptScope。所以问题在于你的 python 源代码或者你如何将 IronPython 包含在 mono 中。
关于dynamic - mono 2.8 支持 'dynamic' 关键字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3920185/