Initialize C# List<T> from IronPython?

喜欢而已 提交于 2019-12-01 23:52:17

问题


I have a relatively deep object tree in C# that needs to be initialized from IronPython.

I'm new to python and I'm struggling with the initialization of arrays.

So as an example - say I have these classes in C#

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

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

I can initialize the array in Class2 like so:

var class2 = new Class2(
    ClassOnes = new List<Class1>()
    {
        new Class1(Foo="bar")
    });

In IronPython - I was trying this:

bar = Class2
bar.ClassOnes = Class1[Class1(Foo="bar")]

But I always get this message:

expected Array[Type], got Class1

Any ideas?


回答1:


You have a couple issues here. First, you're setting bar to the class object Class2 (classes are first-class objects in Python).

You meant to create an instance, like this (with parentheses):

bar = Class2()

To create a List<T> in IronPython, you can do:

from System.Collections.Generic import List

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



回答2:


Made a mistake on the Class2() -- that's what I get for making an example instead of posting real code!!!

For what it's worth - I was able to initialize the List with actual instances like this:

from System.Collections.Generic import List

bar.ClassOnes = List[Class1]([Class1(Foo="bar")])

Thanks much Cameron!



来源:https://stackoverflow.com/questions/6963918/initialize-c-sharp-listt-from-ironpython

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!