将 SortedDictionary 用于 .net(从 C# .dll 导入)
Using SortedDictionary for .net (imported from 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 不允许我调用我在界面中看到的任何 public 成员函数(Add、Clear、ContainsKey 等)。我这样做正确吗?
"In that case it's definitely a syntax issue. You're using C# syntax which the Python interpreter no comprende. I think you want something like SortedDictionary[int, bool] based on some coding examples I just found" @martineau
问题是这样的:
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
这是因为您试图用两个参数实例化 class,而它需要一个具有字典接口的参数。所以这会起作用:
sorted_dict = SortedDictionary[int, bool]({1: True})
编辑:我最初以为您使用的是 IronPython。看起来 Python for .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 等)。我这样做正确吗?
"In that case it's definitely a syntax issue. You're using C# syntax which the Python interpreter no comprende. I think you want something like SortedDictionary[int, bool] based on some coding examples I just found" @martineau
问题是这样的:
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
这是因为您试图用两个参数实例化 class,而它需要一个具有字典接口的参数。所以这会起作用:
sorted_dict = SortedDictionary[int, bool]({1: True})
编辑:我最初以为您使用的是 IronPython。看起来 Python for .NET 使用了类似的方法,所以我相信上面的方法应该仍然有效。