繁体   English   中英

将 Python 列表转换为 .NET IEnumerable?

[英]Converting Python List to .NET IEnumerable?

我试图通过PythonNet库中的clr模块从 Python 脚本调用 C# function。

这个 C# function 采用的 arguments 之一是System.Collections.Generic.IEnumerable类型。 简单地向第一个参数提供所需数据类型的列表会导致'list' value cannot be converted to 'System.Collections.Generic.IEnumerable'错误。

在网上搜索后,假设的 .NET 数据类型应该已经包含在 Python 安装中,我应该可以访问它们。 但是,我不确定如何。

正在做:

from System.Collections.Generic import *

失败,因为找不到模块,同时执行:

import collections

没有命名空间IEnumerable

我 go 如何将 Python 列表转换为System.Collections.Generic.IEnumerable数据类型?

感谢您阅读我的帖子,感谢任何指导。

在从 C#/.NET 导入任何内容之前,您必须从pytho.net package import clr

在Python脚本中折腾了几个小时后,终于想出了解决办法:

首先,必须通过clr模块导入实际的 C# Collections命名空间,如下所示:

clr.AddReference("System.Collections")

然后,必须导入Collections命名空间的特定数据类型:

from System.Collections.Generic import IEnumerable

然后应该能够使用相应的数据类型,并调用它具有的所有 class 函数。 就我而言,我想将 Python List转换为IEnumerable数据类型。 因此,我可以遍历我的 Python List ,并调用IEnumerable class 的Add function(以int数据类型为例):

myList = [1, 2, 3]
myIEnumerable = IEnumerable[int]()

for i in range(len(myList)):
   myIEnumerable.Add(myList[i])

作为旁注,虽然我想从我的 Python 脚本调用的 C# function 的其中一个 arguments 被列为接受一种类型System.Collections.Generic.IEnumerable ,但我设法让它与System.Collections.Generic.List一起工作System.Collections.Generic.List类型代替。 也许它会对其他人有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM