Jim*_*mes 5 c# arrays clr c++-cli list
我想知道为什么这个代码在C++/CLI中不起作用但在C#中该死的很容易?
List<Process^>^ processList = gcnew List<Process^>(
Process::GetProcessesByName(this->processName)););
Run Code Online (Sandbox Code Playgroud)
错误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)));
Run Code Online (Sandbox Code Playgroud)
old*_*inb 10
你需要使用safe_cast
.根据MSDN文档System::Array
,
重要
从.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)));
Run Code Online (Sandbox Code Playgroud)