Skip to main content
 首页 » 编程设计

python之将 SortedDictionary 用于 .net(从 C# .dll 导入)

2024年10月17日5傻小

我目前正在开发一个与 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。看起来 .NET 的 Python 使用了类似的方法,所以我相信上面的方法应该仍然有效。