How to specify a literal initialiser for Stack or Queue?
This:
List<string> set = new List<string>() { "a","b" };
works fine, but:
Stack<string> set = new Stack<string>() { "a","b" };
Queue<string> set = new Queue<string>() { "a","b" };
fails with:
...does not contain a de开发者_开发百科finition for 'Add'
which does make me wonder why the compiler was dumb enough to ask for Add.
So, how should one initialise at a Queue/Stack constructor?
Collection initializers are a compiler feature that call the Add
method with each item you pass.
If there is no Add
method, you can't use it.
Instead, you can call the Stack
or Queue
constructor that takes an IEnumerable<T>
:
var stack = new Stack<int>(new [] { 1, 2, 3 });
in C# 6.0, you can do this:
var stack = new Stack<string> () {"a","b"};
with below extension method
public static class Util
{
public static void Add<T>(this Stack<T> me, T value)
{
me.Push(value);
}
}
精彩评论