0

该程序将 WMI 数据组织成一组类 - 计算机中的每个硬件元素一个类 - 如果存在多个特定硬件元素,则每个类被初始化多次。

有没有一种巧妙的方法可以将这部分代码转换为几个函数调用?我正在考虑一些类似于CreateComponent(ref object dataClass, params string[] WMIClasses);初始化计算机组件的方法,而不是使用 WMI 数据的临时存储并创建一个 for 循环来添加每个实例。

        // These temporary stores fetch WMI data as ManagementObjects
        // Most cases will only need one WMI class.
        ManagementObject[] WMIDataTemp1;
        ManagementObject[] WMIDataTemp2;

        // Fetch data as ManagementObjects
        WMIDataTemp1 = DataRetriever.GetWMIData("Win32_Processor");
        // Loop though each ManagementObject and add a new device for each instance
        foreach (ManagementObject Object in WMIDataTemp1)
        {
            this.Processors.Add(new Processor(Object));
        }

        WMIDataTemp1 = DataRetriever.GetWMIData("Win32_Baseboard");
        WMIDataTemp2 = DataRetriever.GetWMIData("Win32_MotherboardDevice");
        for (int i = 0; i < WMIDataTemp1.Length; i++)
        {
            this.Motherboards.Add(new Motherboard(WMIDataTemp1[i], WMIDataTemp2[i]));
        }
        // And so on for all the other bits of hardware...
4

1 回答 1

0

你试过 LINQ 吗?

Processors = DataRetriever.GetWMIData("Win32_Processor").Select(x => new Processor(x)).ToList();
于 2012-03-12T22:22:38.810 回答