将其缩短为一个函数
本文关键字:一个 函数 | 更新日期: 2023-09-27 18:27:28
此程序将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...
您尝试过LINQ吗?
Processors = DataRetriever.GetWMIData("Win32_Processor").Select(x => new Processor(x)).ToList();