Python中使用System.Collections.Generic List报‘TypeError: type(s) expected’错误求助
解决Python调用.NET泛型List时的TypeError问题
错误原因
你遇到的TypeError: type(s) expected,是因为System.Collections.Generic.List的泛型参数要求是CLR兼容类型,而你定义的MyClass是纯Python类,不属于.NET类型体系,无法直接作为泛型参数使用。
解决方案
方案1:让自定义类继承CLR基类
修改MyClass使其继承自System.Object(.NET所有类型的基类),这样类就会被识别为CLR兼容类型:
import clr clr.AddReference("System.Collections") from System.Collections.Generic import List from System import Object class MyClass(Object): def __init__(self, e=""): self.title = e # 实例化泛型List并操作 li = List[MyClass]() li.Add(MyClass("示例1")) li.Add(MyClass("示例2")) # 转换为Python list正常工作 py_list = list(li) for item in py_list: print(item.title)
方案2:使用Python原生列表中转(无需修改类)
如果不想修改类的继承关系,可以先用Python原生列表存储对象,再按需转换为.NET泛型List(使用List[object]作为兼容类型):
import clr clr.AddReference("System.Collections") from System.Collections.Generic import List class MyClass(object): def __init__(self, e=""): self.title = e # 先用Python列表管理对象 py_li = [MyClass("示例1"), MyClass("示例2")] # 转换为.NET泛型List(用object作为兼容类型) li = List[object]() for item in py_li: li.Add(item) # 转换回Python list正常工作 py_list = list(li)
补充说明
- 如果你使用的是IronPython,纯Python类可以直接与.NET泛型交互,不会出现这个错误;
- 如果你使用的是pythonnet(CPython调用.NET的库),则必须遵循CLR类型要求,方案1是最通用的解决方式。
内容的提问来源于stack exchange,提问作者Justin Xuereb
相关产品推荐
相关产品推荐

