我目前正在开发一个与 C# .dll 交互的 python(针对 .NET)项目。但是,我导入的 SortedDictionary 出现了问题。
这就是我正在做的事情:
import clr
from System.Collections.Generic import SortedDictionary
sorted_dict = SortedDictionary<int, bool>(1, True)
在sorted_dict上调用Count时出现以下错误:
AttributeError: 'tuple' object has no attribute 'Count'
sorted_dict 不允许我调用在界面中看到的任何公共(public)成员函数(Add、Clear、ContainsKey 等)。我这样做正确吗?
最佳答案
问题是这样的:
SortedDictionary<int, bool>(1, True)
<
和>
此行中的符号被视为比较运算符。Python 看到您要求两件事:
SortedDictionary < int
bool > (1, True)
这些表达式之间的逗号使结果成为一个元组,所以你得到 (True, True)
因此。 (Python 2.x 允许您比较任何内容;结果可能没有任何合理的含义,就像这里的情况一样。)
显然,Python 不使用相同的 <...>
泛型类型的语法与 C# 相同。相反,您可以使用 [...]
:
sorted_dict = SortedDictionary[int, bool](1, True)
这仍然不起作用:你得到:
TypeError: expected IDictionary[int, bool], got int
这是因为您试图用两个参数实例化该类,而它需要一个具有字典接口(interface)的参数。所以这会起作用:
sorted_dict = SortedDictionary[int, bool]({1: True})
编辑:我最初假设您使用的是 IronPython。看起来 Python for .NET 使用了类似的方法,所以我相信上面的方法应该仍然有效。
关于python - 使用 SortedDictionary for .net(从 C# .dll 导入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39755973/