在 C# 中可以使用 {a,b,c} 实例化队列吗?
在 C# 中可以做到吗?
Queue<string> helperStrings = {"right", "left", "up", "down"};
或者我必须首先为此生成一个数组?
Is it possible to do that in C#?
Queue<string> helperStrings = {"right", "left", "up", "down"};
or do I have to produce an array first for that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,你不能以这种方式初始化队列。
不管怎样,你可以做这样的事情:
显然,这意味着传递一个数组。
No you cannot initialize a queue in that way.
Anyway, you can do something like this:
and this, obviously, means to pass through an array.
不幸的是没有。
C# 中集合初始值设定项的规则是对象必须 (1) 实现 IEnumerable,并且 (2) 具有 Add 方法。集合初始值设定项
被重写为
,然后产生 temp 中的任何内容。
Queue
实现了 IEnumerable,但它没有 Add 方法;它有一个入队方法。Unfortunately no.
The rule for collection initializers in C# is that the object must (1) implement IEnumerable, and (2) have an Add method. The collection initializer
is rewritten as
and then results in whatever is in temp.
Queue<T>
implements IEnumerable but it does not have an Add method; it has an Enqueue method.由于
Queue
未实现“Add”方法,因此您需要实例化一个IEnumerable
,从中对其进行初始化:As
Queue<T>
does not implement an 'Add' method, you'll need to instantiate anIEnumerable<string>
from which it can be initialized:确切的答案是:是的。
正如 Eric Lippert 所说,它实际上是语法糖,是编译器的语法分析,所以这意味着如果可以让编译器知道 Queue 有一个 Add 方法,然后它就可以“欺骗编译器”。
“扩展方法”可以做到:
然后,这就合法了:
警告:这是一个 Hacky 解决方案,它只是为了解决这个问题,不推荐使用,它有代码味道。
The exact answer is: yes.
As Eric Lippert said, it is actually the syntactic sugars, is the syntax analysis of the compiler, so it means that if the compiler can be made aware that Queue has an Add method, then it can "fool the compiler".
"Extension method" can made it:
Then, this becomes legal:
Warning: This is a Hacky solution, it just for solved this question, not recommend to use, it has code smell.