【问题标题】:How to solve the "String" in "for each" loop如何解决“for each”循环中的“String”
【发布时间】:2013-03-21 19:56:19
【问题描述】:

我的任务是在单击按钮后打开多个文件,并读取所有选定的文件。

我在 c# 中找到了一个 foreach 函数的示例,但我想用 C++ 编写它。我应该如何实际转换它?

显示错误System::String, cannot use this type here without top level '^'.

我还是新手。有没有人可以给点建议?

非常感谢。

下面是我写的代码

Stream^ myStream;
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;

openFileDialog1->InitialDirectory = "c:\\";
openFileDialog1->Title = "open captured file";
openFileDialog1->Filter = "CP files (*.cp)|*.cp|All files (*.*)|*.*|txt files (*.txt)|*.txt";
openFileDialog1->FilterIndex = 2;
//openFileDialog1->RestoreDirectory = true;
openFileDialog1->Multiselect = true;

if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )
{
    **for each (String line in openFileDialog1->FileName)** 
         System::Diagnostics::Debug::WriteLine("{0}",line);
    myStream->Close();
}

【问题讨论】:

    标签: string c++-cli managed-c++


    【解决方案1】:

    根据返回的 Container 类型,<algorithm>-header 中定义了一个 std::for_each。 函数如下所示:

    #include <algorithm>
    
    std::for_each(InputIterator first, InputIterator last, Function fn);
    

    您需要提供两个iterators,一个用于Container 的开头,一个用于迭代器的结尾。作为第三个参数,您可以提供一个函数(函数对象)并对当前参数进行操作。

    请参阅here 以获取更多参考。

    当我从MSDN 得到它时,属性SafeFileNames 返回一个array&lt;String^&gt;

    System::Array 提供了一个名为Array::ForEach 的静态方法。你需要这样称呼它

    System::Action<T> myAction; // You will Need to provide a function here to be used on every filename.
    System::Array::ForEach(openFileDialog1->SafeFileNames, myAction);
    

    这与 C# 中的 foreach 最接近。

    here 中查找System::Array::ForEach,在here 中查找OpenFileDialog::SafeFileNames

    【讨论】:

    • 这属于C++-STL,因此是可移植的。您可以在那里毫无顾虑地使用它。
    • 是唯一的方法吗?在浏览了您给定的链接后,我真的不明白这一点。对不起,如果这个问题有点愚蠢,因为我对它还是很陌生。无论如何,非常感谢您的宝贵时间。
    • 嗯,std::foreach 最接近您正在寻找的内容。以这种方式看待它:您将在C# 中的foreach() {} 中提供的内容作为std::foreach 的第三个参数提供。当然会有使用迭代器的正常方式。
    猜你喜欢
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    相关资源
    最近更新 更多