【发布时间】:2018-12-18 22:34:07
【问题描述】:
我正在尝试跳过 Visual C++ 管理的 String^ 或 String^ 数组中的一行,但我还没有找到任何简单的方法。事实上,我花了两天时间在 C# 中花费不到 30 秒的时间。 C# Enumerable 中有一个方法 .Skip()
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.skip?view=netframework-4.7.2
如果可能的话,我想为 VC++ 提供类似的东西。
这是我尝试过的:
auto a = gcnew cli::array<String ^>{ "Alpha", "Bravo", "Charlie", "Delta" };
auto xs = gcnew System::Collections::Generic::List<String^>(a);
System::Collections::Generic::IEnumerator<String^>^ e = xs->GetEnumerator();
e->MoveNext();
^^ 抛出异常类 System::EventArgs 没有成员“MoveNext”
编辑:我知道是什么导致了异常 System::EventArgs has no member "MoveNext" .. 在 Visual Studio 中使用 ' e ' 会导致编译器认为我在 e) click_method 中指的是 EventArgs 的 e 。 . 我切换到另一个名称,它填充为:System.Collections.Generic.List`1+Enumerator[System.String]
我也尝试过引用 System::Linq 然后
System::Collections::Generic::List<String ^>^ _list = gcnew System::Collections::Generic::List<String ^>(System::IO::File::ReadAllLines(filename));
System::Collections::Generic::List<String ^>^ _list2 = _list->Skip(1);
这似乎可以在 C# 中工作,但得到以下异常
类 System::Collections::Generic::List 没有成员跳过
所以 .NET 库在 CLI / C++ 中不起作用
我尝试的另一件事是:
System::Collections::Generic::List<String ^>^ _list = gcnew System::Collections::Generic::List<String ^>(System::IO::File::ReadAllLines(filename));
System::Collections::Generic::List<String ^>^ _list2 = _list->RemoveAt(0);
但有异常: “void”类型的值不能用于初始化 System::Collections::Generic::List^
类型的实体如果可能的话,我正在尝试不使用 marshal_string 来做到这一点,但我愿意接受任何建议,因为我一直在努力解决这个问题,不知道还能尝试什么 =[
【问题讨论】:
-
扩展方法只是静态方法,所以我猜你可以手动调用它:
Enumerable::ToList(Enumerable::Skip(_list, 1));但不建议这是最好的方法。 (注意Skip的返回值不是List<>- 注意你的类型,这对你有很大帮助。)见this answer。 -
请注意,这对我来说似乎是 XY Problem - 克隆
List^以删除第一个元素是处理列表的一种非常低效的方法。 -
@NetMage /* 不错...这绝对有帮助,但我仍然没有跳过一行*/
-
我不清楚在
String^或List<String^>^的上下文中“跳过一行”是什么意思? -
@NetMage /* 是的,那是因为我最初想用单个 String^ 来实现这一点,但后来由于无法找到足够的资源而切换到 String^ 数组。我想出了如何将其作为一个数组而不是作为单个 String^ */
标签: string list linq visual-c++ skip