2012-03-12 61 views
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... 
+2

這可能更適合codereview.stackexchange.com – ramblinjan 2012-03-12 22:20:06

+0

我不知道這一點,謝謝。我會先看看有沒有人提出答案。 – CJxD 2012-03-12 22:42:43

回答

0

您是否試過LINQ?

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

嗯,不太有效,因爲一些硬件類需要多個WMI類來初始化。 – CJxD 2012-03-12 22:25:06

+0

另外,我的目標框架是2.0,我不認爲包含LINQ。 – CJxD 2012-03-12 22:31:59