ironpython - 从 IronPython 初始化 C# List<T>?

标签 ironpython

我在 C# 中有一个相对较深的对象树,需要从 IronPython 初始化。

我是 python 的新手,正在为数组的初始化而苦苦挣扎。

举个例子 - 假设我在 C# 中有这些类

public class Class1
{
    public string Foo {get;set;}
}

public class Class2
{
    List<Class1> ClassOnes {get;set;}
}

我可以像这样初始化 Class2 中的数组:
var class2 = new Class2(
    ClassOnes = new List<Class1>()
    {
        new Class1(Foo="bar")
    });

在 IronPython 中 - 我正在尝试这个:
bar = Class2
bar.ClassOnes = Class1[Class1(Foo="bar")]

但我总是收到这条消息:

expected Array[Type], got Class1



有任何想法吗?

最佳答案

你在这里有几个问题。首先,您正在设置 bar到类对象 Class2 (类是 Python 中的一流对象)。

您打算创建一个实例,如下所示(带括号):

bar = Class2()

创建一个 List<T>在 IronPython 中,您可以执行以下操作:
from System.Collections.Generic import List

# Generic types in IronPython are supported with array-subscript syntax
bar.ClassOnes = List[Class1]()
bar.ClassOnes.Add(Class1())

关于ironpython - 从 IronPython 初始化 C# List<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6963918/

相关文章:

python - 使用ironpython共享文件夹

ironpython - 如何在 Spotfire 中使用 IronPython 获取列的外部名称?

python - 无法找到来自 NuGet 的 IronPython StdLib

c# - IronPython 是否允许我在 C# 项目中使用 Python,而不添加新的部署要求?

c# - 如何在 IronPython 中调用 C#/.NET 命名空间?

c# - 从 Iron Python 脚本(从 C# 脚本引擎调用)调用 Python 脚本时出现问题

nhibernate - 如何从 IronPython 配置 NHibernate 类映射?

c# - 通过 IronPython 在 C# 中使用 NLTK

ironpython - IronPython 类型的命名空间和程序集名称如何工作?

IronPython 的核心 Python 模块的 C# 或其他 .NET 等效项?