C#/ IronPython Interop和"float"数据类型

Ada*_*ile 5 c# ironpython c#-4.0

使用一些IronPython脚本作为插件的项目,使用C#编码的功能.在我的一个C#类中,我有一个类型为的属性:

Dictionary<int, float>
Run Code Online (Sandbox Code Playgroud)

我从IronPython代码中设置了该属性的值,如下所示:

mc = MyClass()
mc.ValueDictionary = Dictionary[int, float]({1:0.0, 2:0.012, 3:0.024})
Run Code Online (Sandbox Code Playgroud)

但是,当运行这段代码时,它会抛出以下异常:

Microsoft.Scripting.ArgumentTypeException was unhandled by user code
  Message=expected Dictionary[int, Single], got Dictionary[int, float]
Run Code Online (Sandbox Code Playgroud)

为了使事情变得更奇怪,最初使用的是C#代码

Dictionary<int, double>
Run Code Online (Sandbox Code Playgroud)

但是我在IronPython中找不到"双重"类型,一想到就"浮动"并且工作正常,没有错误.但是现在它在两端使用float(应该从一开始就使用它)它会出错,并认为C#代码使用的是"Single"数据类型?!

我甚至在对象浏览器中检查了C#库,当然,它显示为使用"float"类型而不是"Single"

Phi*_*ier 7

我真的没有在这里看到一个问题,你自己也非常回答了一切.我想你只是在问,因为你很困惑.所以让我们清楚一点:

C#有两种浮点类型:( float一个System.Single MSDN的缩写,32位长的double关键字)和(System.Double MSDN的关键字,64位长).

另一方面,Python使用float关键字/类型来存储双精度浮点数,如python文档所述:

浮点数在C中使用double实现.除非您碰巧知道正在使用的机器,否则所有关于其精度的投注都将关闭.

为此,在x86架构上,它是64位长.这就是IronPython将python float视为.NET 的原因System.Double.

也就是说,这两种方法都有效:

C#:

Dictionary<int, float> single_precision_dict;
Dictionary<int, double> double_precision_dict;
Run Code Online (Sandbox Code Playgroud)

IronPython的:

single_precision_dict = Dictionary[int, Single]({1:0.0, 2:0.012, 3:0.024})
double_precision_dict = Dictionary[int, float]({1:0.0, 2:0.012, 3:0.024})
Run Code Online (Sandbox Code Playgroud)