python - 使用 SortedDictionary for .net(从 C# .dll 导入)

标签 python .net dictionary python.net

我目前正在开发一个与 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/

相关文章:

.net - 如何在 Linq 中将整数列表转换为字符串数组?

list - Flutter:通用列表处理不同的键值对

javascript - 用 n 个 gps 坐标测量区域

python - 在 Python 中读取 ASCII 文件(numpy-array?)

python - Python 异常后是否需要返回语句?

c# - 为了 "purely documenting"目的,我应该在我的方法中捕获异常吗?

c# - 如何在查询 C# 中使用 Linq 和 Dictionary 从 List<> 获取元素?

python - 如何通过继承避免 ModelForms 中的代码重复

python - 在抛出 subprocess.TimeoutExpired 后杀死 Python 子进程的子进程

c# - 如果没有打开文件的程序,则捕获文件的打开