“对于每个” C++CLI 中的语句
array<int> ^ints = gcnew array<int>{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for each(int i in ints)
if(i % 2 == 0)
Debug::WriteLine("Even\n");
else
Debug::WriteLine("Odd\n");
为什么上面的编译失败呢? 如果我使用 for(int i; ...) 或将 if-else 括在大括号内,则效果很好。 我知道手册明确指出需要大括号,但我想知道为什么会偏离预期行为?
array<int> ^ints = gcnew array<int>{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for each(int i in ints)
if(i % 2 == 0)
Debug::WriteLine("Even\n");
else
Debug::WriteLine("Odd\n");
Why does the above fail to compile? It works fine if I use a for(int i; ...)
or if I enclose the if-else
within braces. I know that the manual clearly indicates that braces are required, but I want to know why this departure from expected behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我找不到任何官方文档,但我可以确认您所看到的行为。 看起来编译器过于积极地寻找
foreach
后面的单个语句,以至于将else
与if
分开。 它会编译它,就好像您编写了以下内容一样,这显然是不正确的。这显然与常规 C++
for
循环的行为方式不同,因此您可能希望在 http://connect.microsoft.com。I can't find any official documentation on it, but I can confirm the behavior you're seeing. It simply appears that the compiler is overly aggressive about finding the single statement following the
for each
, to the point of splitting theelse
from theif
. It compiles it as if you had written the following, which is clearly incorrect.This is obviously different to how a regular C++
for
loop behaves, so you may wish to file a bug at http://connect.microsoft.com.我不是 CLI 导出人员,但我相信for every (i in ints)
就是您所追求的。编辑
我检查了可用的 C++ 源代码,我们正在使用:
是否可能需要使用牙套? 我手边没有 MSFT 编译器,否则我会尝试以下操作:
I'm not a CLI export but I believe thatfor each (i in ints)
is what you are after.Edit
I checked the C++ source that I have available and we are using:
Is it possible that the braces are required? I don't have an MSFT compiler handy or I would try the following: