Collection Initialization Syntax, what for?
We just can use function like
public static List<T> New<T>(params T[] items) {
return new List<T>(items);
}
and more important it's better
var list = new List<int> {1,2,3};
var list = List.New(1,2,3);
So, when we really need to use it?
Dictionary
public static Dictionary<T, K> New<T, 开发者_StackOverflowK>(T key, K value) {
return new Dictionary<T,K>().FAdd(key, value);
}
var dict = new Dictionary<int, string>(){
{1, "a"},
{2, "b"}
};
var dict = Dict.New(1,"a").FAdd(2, "b");
Why it's better, type inference
var x = new Dictionary<string, List<int>>(){
{"a", new List<int>{1}},
{"b", new List<int>{2}},
}
var x = Dict.New("a", List.New(1)).FAdd("b", List.New(2));
This requires adding a new function in your type. Collection initializers don't require any external code in order to work - you can use them for any compatible collection type, and it's handled by the compiler automatically.
In addition, using the language functionality instead of rolling your own method will make the code more obvious to other developers. Since you're using a standard language feature, the intent becomes obvious. Using an extension method can easily mask your intent.
So, when we really need to use it?
You never need to use it. Like all language features, it's a tool - you can choose to use or to ignore, at your discretion as a developer.
One issue with your sample is that it's much less effecient than a collection initializer statement would be. The use of params
forces the collection to essentially be created twice
- Once to create a .Net Array for the values
- Creating the actual collection
Collection initializers on the other hand just create the second collection.
Overall though one of the primary reasons for collection initializers is not having to write this API. There are a variety of collections in the framework with an unfortunate variety of creating patterns. Many don't have the constructor taking IEnumerable
and instead force a set of individual Add calls. You end up writing this method over and over again.
Collection initializers let you avoid writing it altogether and instead just use the collection out of the box.
No, it is not better. Collection Initialization Syntax support any class that: 1) Has Add
method 2) Implements IEnumerable
. Thus it works with every collection even with Dictionary
, not List
only. Plus your method requires creation of array, small but excessive overhead. Initialization doesn't have it.
精彩评论