示例代码:
struct Item
{
public int a;
public string b;
};
Item[] items = {
new Item { a = 12, b = "Hello" },
new Item { a = 13, b = "Bye" }
};
引入参数化构造函数的附加选项:
struct Item
{
public int a;
public string b;
public Item(int a, string b)
{
this.a = a;
this.b = b;
}
};
Item[] items = {
new Item( 12, "Hello" ),
new Item( 13, "Bye" )
};
正如@YoYo 建议的那样,删除了new[]
part.
棘手的方法(对于以下情况new Item
太打扰你了)
声明新类:
class Items : List<Item>
{
public void Add(int a, string b)
{
Add(new Item(a, b));
}
}
然后你可以将其初始化为:
Items items = new Items {
{ 12, "Hello" },
{ 13, "Bye" }
};
您还可以申请.ToArray
的方法List
得到一个数组Item
s.
Item[] items = new Items {
{ 12, "Hello" },
{ 13, "Bye" }
}.ToArray();
该技巧基于集合初始值设定项(http://msdn.microsoft.com/en-us/library/bb384062.aspx http://msdn.microsoft.com/en-us/library/bb384062.aspx):
通过使用集合初始值设定项,您不必指定对Add源代码中类的方法;编译器添加调用。