简体   繁体   English

最短的内联集合初始化程序? C#

[英]Shortest inline collection initializer? C#

What is the neatest / shortest way I can write an inline collection initializer? 我可以编写内联集合初始化程序的最简单/最短的方法是什么?

I dont care about reference names, indexes are fine, and the item only needs to be used in the scope of the method. 我不关心引用名称,索引很好,只需要在方法范围内使用该项目。

I think an anonymous type collection would be messier because I would have to keep writing the key name every time. 我认为匿名类型集合会更加混乱,因为我每次都必须继续写密钥名称。

I've currently got 我现在有

var foo = new Tuple<int, string, bool>[] 
{ 
   new Tuple<int, string, bool>(1, "x", true), 
   new Tuple<int, string, bool>(2, "y", false) 
};

Im hoping c# 4.0 will have something ive missed. 我希望c#4.0会有一些我错过的东西。

你可以得到的最短的是使用Tuple.Create而不是new Tuple

var foo = new [] { Tuple.Create(1, "x", true), Tuple.Create(2, "y", false) };

a bit less space in there if you use Tuple.Create(1,"x",true) instead of the new thing - and you can strip the new Tuple<tint, string, bool> stuff before the array too: 如果你使用Tuple.Create(1,"x",true)代替新东西,那里的空间会少一些 - 你也可以在数组之前new Tuple<tint, string, bool>东西:

var foo = new [] { Tuple.Create(1, "x", true), Tuple.Create(2, "y", false) };

or take this one: 或者拿这个:

Func<int, string, bool, Tuple<int, string, bool>> T = (i, s, b) => Tuple.Create(i,s,b);
var foo = new [] { T(1, "x", true), T(2, "y", false) };

or even 甚至

Func<int, string, Tuple<int, string, bool>> T = (i, s) => Tuple.Create(i,s,true);
Func<int, string, Tuple<int, string, bool>> F = (i, s) => Tuple.Create(i,s,false);
var foo = new [] { T(1, "x"), F(2, "y") };

You can also add a 你也可以添加一个

using MyTuple= System.Tuple<int, string, bool>;

at the end of your using declarations and then use MyTuple instead of the longer version. using声明的最后,然后使用MyTuple而不是更长的版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM