[英]Shorthand for single item to collection c#
I have a lot of code that takes on the following pattern我有很多代码采用以下模式
void Add(int foo)
{
$my question
}
void Add(List<int> bar)
{
//do stuff
}
I was wondering (other than writing an extension method) if there was something 'shorter than writing:我想知道(除了写一个扩展方法)是否有一些比写更短的东西:
Add(new List<int>(new int[]{foo}));
everytime I wanted to call the second method.每次我想调用第二种方法。 Hoping to find a gem ive missed in the .net library.
希望找到 .net 库中遗漏的宝石。
Assuming you're using C# 3 or higher, you can use a collection initializer :假设您使用的是 C# 3 或更高版本,您可以使用集合初始化程序:
Add(new List<int> { foo });
This is equivalent to:这相当于:
List<int> tmp = new List<int>();
tmp.Add(foo);
Add(tmp);
I am not sure if it is sufficiently shorter enough, but this will work as well:我不确定它是否足够短,但这也可以:
Add(new List<int> { foo });
If you can modify the second method, it might be better if it was如果你可以修改第二种方法,它可能会更好
void Add(params int[] bar)
{
}
Then you can call it like Add(foo, foo2, foo3)
or Add(myList.ToArray())
然后您可以将其称为
Add(foo, foo2, foo3)
或Add(myList.ToArray())
Have a look at the params keyword .看看params 关键字。
You can use a collection initializer directly on the List:您可以直接在 List 上使用集合初始化程序:
Add(new List<int> { foo });
I tend to use IEnumerable
for sequence arguments and new []
syntax to pass an implicitly typed array:我倾向于使用
IEnumerable
序列 arguments 和new []
语法来传递隐式类型数组:
public void Add (IEnumerable<int> bar)
{
}
// accepts:
Add (new List<int> { 1, 2, 3 });
Add (Enumerable.Range (1, 10));
Add (new [] { 1 });
As a variant, you may want to define an “amplifying” extension method:作为一种变体,您可能想要定义一个“放大”扩展方法:
public IEnumerable<T> Amplify (T item)
{
yield return item;
}
Add (1.Amplify ())
You need to refactor code something similar to the follow:您需要重构代码类似于以下内容:
void Add(int bar)
{
//Code for single element
}
void Add(List<int> foo)
{
foreach(int i in foo)
{
Add(i);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.