“对于每个” C++CLI 中的语句

发布于 2024-07-26 22:25:47 字数 330 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光病人 2024-08-02 22:25:48

我找不到任何官方文档,但我可以确认您所看到的行为。 看起来编译器过于积极地寻找 foreach 后面的单个语句,以至于将 elseif 分开。 它会编译它,就好像您编写了以下内容一样,这显然是不正确的。

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");

这显然与常规 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 the else from the if. It compiles it as if you had written the following, which is clearly incorrect.

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");

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.

无所的.畏惧 2024-08-02 22:25:48

我不是 CLI 导出人员,但我相信 for every (i in ints) 就是您所追求的。

编辑

我检查了可用的 C++ 源代码,我们正在使用:

for each (int i in ints) {
   // body
}

是否可能需要使用牙套? 我手边没有 MSFT 编译器,否则我会尝试以下操作:

for each (int i in ints) {
    if(i % 2 == 0) {
        Debug::WriteLine("Even\n");
    } else {
        Debug::WriteLine("Odd\n");
    }
}

I'm not a CLI export but I believe that for each (i in ints) is what you are after.

Edit

I checked the C++ source that I have available and we are using:

for each (int i in ints) {
   // body
}

Is it possible that the braces are required? I don't have an MSFT compiler handy or I would try the following:

for each (int i in ints) {
    if(i % 2 == 0) {
        Debug::WriteLine("Even\n");
    } else {
        Debug::WriteLine("Odd\n");
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文