C# 访问 ManagementObjectCollection 中的管理对象
我试图在不使用 foreach 语句的情况下访问 ManagementObjectCollection 中的 ManagementObjects,也许我遗漏了一些东西,但我不知道该怎么做,我需要执行如下操作:
ManagementObjectSearcher query = new ManagementObjectSearcher(
"select Name, CurrentClockSpeed from Win32_Processor");
ManagementObjectCollection queryCollection = query.Get();
ManagementObject mo = queryCollection[0];
I'm trying to access ManagementObjects in ManagementObjectCollection without using a foreach statement, maybe I'm missing something but I can't figure out how to do it, I need to do something like the following:
ManagementObjectSearcher query = new ManagementObjectSearcher(
"select Name, CurrentClockSpeed from Win32_Processor");
ManagementObjectCollection queryCollection = query.Get();
ManagementObject mo = queryCollection[0];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ManagementObjectCollection 实现 IEnumerable 或 ICollection,因此您必须迭代它通过 IEnumerable (即 foreach)或通过 ICollection 复制到数组。
但是,由于它支持 IEnumerable,因此您可以使用 Linq :
OfType
是必需的,因为 ManagementObjectCollection 支持 IEnumerable 但不支持 T 的IEnumerable。ManagementObjectCollection implements IEnumerable or ICollection, so either you must iterate it via IEnumerable (ie foreach) or CopyTo an array via ICollection.
However since it supports IEnumerable you can use Linq :
OfType<ManagementObject>
is required because ManagementObjectCollection supports IEnumerable but not IEnumerable of T.您不能直接从 ManagementObjectCollection (也不能从整数索引器)调用 linq。
您必须首先将其转换为 IEnumerable:
You can not directly call linq from ManagementObjectCollection (nor an integer indexer).
You have to cast it to IEnumerable first:
ManagementObjectCollection 不实现索引器,但是如果您使用 linq,您可以使用 FirstOrDefault 扩展函数,但使用 .net 3 或更早版本的极客(比如我仍在使用 1.1)可以使用以下代码,这是获取第一项的标准方法来自任何实现了 IEnumerable 接口的集合。
以下是从任何索引检索 ManagementObject 的两种不同方法
或
ManagementObjectCollection does not implements Indexers, but yes you can you FirstOrDefault extension function if you are using linq but geeks who are using .net 3 or earlier (like me still working on 1.1) can use following code, it is standard way of getting first item from any collection implemented IEnumerable interface.
following are two different ways to retrieve ManagementObject from any index
OR