如何在C#中在单个数组中组合多个自定义对象?
我设计了一个自定义对象列表, 并在此处添加更多详细信息:如何在C#中在单个数组中组合多个自定义对象?,c#,arraylist,dynamic,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 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());
}
}
试试这个
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();
var list=new list(){
新客户名单{
Name=“a1”,
Path=“c:/”,
尺寸=1111,
值=23
},
新客户名单{
Name=“a2”,
Path=“c:/”,
尺寸=222,
值=66
}
}
var array=list.ToArray();
您已经用()
而不是{}
初始化了数组。
正确的数组初始化语法如下:
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
},
. . .
};
你的实际目标是什么?我的意思是,这个代码应该解决什么问题?这不是一个错误的代码,它会工作得很好,你有什么问题当我运行上一个代码时,它显示“CS1586 C#Array creation must have Array size或Array initializer”@kkasp我现在明白了问题所在,用
{}
代替()
初始化数组时。我想按任意大小分配动态多个列表,但不要先分配数组大小。很好,很容易出错
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
},
. . .
};