问题
What is the quickest in C# 2.0
to create a one-element list out of a single object?
eg:
MyObject obj = new MyObject();
List<MyObject> list = new List<MyObject> { obj }; // is this possible?
回答1:
Your sample code
List<MyObject> list = new List<MyObject> { obj };
uses a collection initializer, which was not available in C# 2.0. You could use an array initializer, instead:
List<MyObject> list = new List<MyObject>(new MyObject[] { obj });
Or, just make the list and add the object:
List<MyObject> list = new List<MyObject>(1);
list.Add(obj);
Note that "singleton" usually refers to the singleton pattern; as you see from the comments, it's confusing to use that term to refer to a collection containing one element.
回答2:
You could create the following extension and just call it on any object you want to create a list of itself.
The only down side is that it would pollute the extension space... So I would only do this if you found yourself using it often.
public static partial class Extensions
{
public static List<T> ToListOfSelf<T>(this T item)
{
return new List<T>() { item };
}
}
e.g. myObject.ToListOfSelf();
来源:https://stackoverflow.com/questions/13998343/quick-way-to-turn-object-into-single-element-list