对.net使用SortedDictionary(从C#.dll导入)

油菜

我目前正在研究与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不允许我调用我在界面中看到的任何公共成员函数(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

这是因为当您想要一个具有字典接口的单个​​参数时,您试图使用两个参数实例化该类。所以这将工作:

sorted_dict = SortedDictionary[int, bool]({1: True})

编辑:我最初认为您正在使用IronPython。看起来.NET的Python使用了类似的方法,因此我相信上面的方法仍然可以使用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章