如何在C#中的单个数组中组合多个自定义对象?

时间:2019-06-06 05:20:07

标签: c# arraylist dynamic

我设计了一个自定义对象列表, 并在此处添加更多详细信息:

public static List<CustomList> MyLists = new List<CustomList>();
public class CustomList
{
    public string Name { get; set; } //
    public string Path{ get; set; } //
    public long Size { get; set; }
    public int Value { get; set; }
}
private void Form1_Load()
{
    CustomList[] list = new CustomList[5];
    list[0] = new CustomList
    {
        Name = "a1",
        Path = "c:/",
        Size = 1111,
        Value = 23
    };
    list[1] = new CustomList
    {
        Name = "a2",
        Path = "c:/",
        Size = 222,
        Value = 66
    };

    //add to MyLists
    for (int i = 0; i < list.Count(); i++)
    {
        MyLists.Add(list[i]);
    }
}

private void button1_Click(object sender, EventArgs e)
{
    //show all MyLists
    foreach (CustomList element in MyLists)
    {
        if (element != null)
        Console.WriteLine(element.Size.ToString());
    }
}

总而言之,我想创建一个动态对象数组,就像在PHP代码中那样:

<?php
$list = array(
    array(
        "name" => "a1",
        "Path" => "c:/",
        "Size" => 1111,
        "Value" => 23
    ),
    array(
        "name" => "a2",
        "Path" => "c:/",
        "Size" => 222,
        "Value" => 34
    ),

    //...
    // more than 10 arrays or any number sets ...
    //...
);

所以我尝试用C#编写代码, 我还添加了一些代码并一次又一次地修改了某些部分, 但这是错误的,我可以修复它还是C#不支持它?

我创建了一个Object类的数组,并将任何东西分配给这样的数组。

//it is a wrong code
CustomList[] list = new CustomList[](
new CustomList{
    Name = "a1",
    Path = "c:/",
    Size = 1111,
    Value = 23
},
new CustomList{
    Name = "a2",
    Path = "c:/",
    Size = 222,
    Value = 66
}
);

2 个答案:

答案 0 :(得分:1)

您已使用()而不是{}初始化了数组。 正确的数组初始化语法是这样的:

CustomList[] list = new CustomList[]
{
    new CustomList{
        Name = "a1",
        Path = "c:/",
        Size = 1111,
        Value = 23
    },
    new CustomList{
        Name = "a2",
        Path = "c:/",
        Size = 222,
        Value = 66
    }
};

或者您可以这样做:

CustomList[] list = new []
{
    new CustomList{
        Name = "a1",
        Path = "c:/",
        Size = 1111,
        Value = 23
    },
    new CustomList{
        Name = "a2",
        Path = "c:/",
        Size = 222,
        Value = 66
    }
};

甚至:

var list = new []
{
    new CustomList{
        Name = "a1",
        Path = "c:/",
        Size = 1111,
        Value = 23
    },
    .  .  .
};

答案 1 :(得分:0)

尝试

var list = new List<CustomList>() { 
    new CustomList{
        Name = "a1",
        Path = "c:/",
        Size = 1111,
        Value = 23
    },
    new CustomList{
        Name = "a2",
        Path = "c:/",
        Size = 222,
        Value = 66
    } 
    }

    var array = list.ToArray();