开发者

Initialize C# List<T> from IronPython?

开发者 https://www.devze.com 2023-03-26 12:11 出处:网络
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.

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 = Cla开发者_JAVA百科ss1[Class1(Foo="bar")]

But I always get this message:

expected Array[Type], got Class1

Any ideas?


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())


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消