我想知道为什么这段代码在C ++ / CLI中不起作用但在C#中该死的很容易?
List<Process^>^ processList = gcnew List<Process^>(
Process::GetProcessesByName(this->processName)););
错误C2664:'System :: Collections :: Generic :: List :: List(System :: Collections :: Generic :: IEnumerable ^)':无法将参数1从'cli :: array ^'转换为'System :: Collections :: Generic :: IEnumerable ^'
这是我想出的。做得很好。 :)
List<Process^>^ processList = gcnew List<Process^>(
safe_cast<System::Collections::Generic::IEnumerable<Process^>^>
(Process::GetProcessesByName(this->processName)));
答案 0 :(得分:9)
您需要使用safe_cast
。根据{{3}},
重要
从.NET Framework 2.0开始,Array类实现
System.Collections.Generic::IList<T>
,System.Collections.Generic::ICollection<T>
和System.Collections.Generic::IEnumerable<T>
通用接口。这些实现在运行时提供给数组,因此文档构建工具不可见。因此,通用接口不会出现在 Array 类的声明语法中,并且没有可通过将数组转换为通用接口类型来访问的接口成员的参考主题(显式接口实现)。将数组转换为其中一个接口时要注意的关键是添加,插入或删除元素的成员抛出NotSupportedException
。
如您所见,强制转换必须在运行时在C ++中显式完成,例如
List<Process^>^ processList = gcnew List<Process^>(
safe_cast<IEnumerable<T> ^>(
Process::GetProcessesByName(this->processName)));