将其缩短为一个函数

时间:2012-03-12 22:18:06

标签: c# function for-loop paramarray

该程序将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...

1 个答案:

答案 0 :(得分:0)

你试过LINQ吗?

Processors = DataRetriever.GetWMIData("Win32_Processor").Select(x => new Processor(x)).ToList();