I have design a custom object list, and adding more details in here:
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());
}
}
In summary, I want to create a dynamic object arrays simulate like in PHP code:
<?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 ...
//...
);
So I try to write a code in C#, I am also have added some code and modify some part again and again, but it is wrong, can I to fix it or it is not support in C#?
I create an array of Object class and assign anything to the array like this.
//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
}
);
You have initialized your array with ()
instead of {}
. The correct array initialization syntax is this one:
CustomList[] list = new CustomList[]
{
new CustomList{
Name = "a1",
Path = "c:/",
Size = 1111,
Value = 23
},
new CustomList{
Name = "a2",
Path = "c:/",
Size = 222,
Value = 66
}
};
or you can do:
CustomList[] list = new []
{
new CustomList{
Name = "a1",
Path = "c:/",
Size = 1111,
Value = 23
},
new CustomList{
Name = "a2",
Path = "c:/",
Size = 222,
Value = 66
}
};
or even:
var list = new []
{
new CustomList{
Name = "a1",
Path = "c:/",
Size = 1111,
Value = 23
},
. . .
};
try this
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.