gpt4 book ai didi

c# - 在 CLR C++ 中用数组初始化 List

转载 作者:太空狗 更新时间:2023-10-29 22:27:29 24 4
gpt4 key购买 nike

我想知道为什么这段代码在 C++/CLI 中不起作用,但在 C# 中却很容易?

List<Process^>^ processList = gcnew List<Process^>(
Process::GetProcessesByName(this->processName)););

error C2664: 'System::Collections::Generic::List::List(System::Collections::Generic::IEnumerable ^)' : cannot convert parameter 1 from 'cli::array ^' to 'System::Collections::Generic::IEnumerable ^'

这是我想出的。做得很好。 :)

List<Process^>^ processList = gcnew List<Process^>(
safe_cast<System::Collections::Generic::IEnumerable<Process^>^>
(Process::GetProcessesByName(this->processName)));

最佳答案

您需要使用 safe_cast .根据MSDN documentation on System::Array ,

Important

Starting with the .NET Framework 2.0, the Array class implements the System.Collections.Generic::IList<T>, System.Collections.Generic::ICollection<T>, and System.Collections.Generic::IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.

如您所见,强制转换必须在运行时在 C++ 中显式完成,例如

List<Process^>^ processList = gcnew List<Process^>(
safe_cast<IEnumerable<T> ^>(
Process::GetProcessesByName(this->processName)));

关于c# - 在 CLR C++ 中用数组初始化 List<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12152913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com