c#
  • collections
  • enumeration
  • 2014-02-11 143 views 0 likes 
    0

    使用這個函數對象:訪問從對象集合

    public bool CheckCallerStatus(string stConsumerName) 
        { 
         SelectQuery selectQuery = new SelectQuery("select ExecutablePath from Win32_Process where name='" + 
           stConsumerName + "'"); 
         using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery)) 
         { 
          ManagementObjectCollection moc = searcher.Get(); 
          if (moc.Count > 1) 
          { 
           return true; // OK process is running 
          } 
          return false; 
         } 
        } 
    

    我可以檢查是否這個過程中,通過在作爲stConsumerName,是一個積極的過程(我用moc.Count > 1而不是moc.Count > 0因爲我打電話函數,我正在觀察並試圖查看是否還有其他活動進程)。我的過程的每個實例都作爲對象存儲在ManagementObjectCollection moc中。

    現在,我想要得到過程的路徑。我相信這個信息被存儲在一個對象在moc和簡單foreach,就像這樣:

    string stFilePath = Empty.String; 
    foreach (ManagementObject process in moc) 
    { 
        stFilePath = process["ExecutablePath"].ToString(); 
    } 
    

    將返回path豐厚。

    正如你可以看到我的process["ExecutablePath"]的值存儲到string(而不是一個Listarray或諸如此類),因爲我只關心第一個進程的路徑(我假設返回的所有進程在moc是我的過程[這個名字足夠獨特])。

    我的問題是:如何訪問在ManagementObjectCollection任何一個對象?這樣我可以設置stFilePath = process["ExecutablePath"];由於moc不支持索引,moc.First()moc.Single()不會幫助。

    和相關的問題:ManagementObjectClass有一個方法GetEnumerable()。我環顧四周(當然還有MSDN參考資料),我真的不明白。 是否GetEnumerable()返回索引集合?

    +0

    你可以在'foreach'裏面使用'break statement'嗎? –

    +1

    使用'foreach'獲取一個項目,然後使用'break'並不是一個好主意,因爲'foreach'用於迭代多個項目。稍後嘗試維護代碼時,這可能會有點混淆。 – Steve

    +0

    因此'ManagementObjectCollection'實現了IEnumerable接口的非泛型版本嗎? – Grzenio

    回答

    2

    您可以獲得第一個對象usig LINQ:moc.First(),或者如果您想驗證,只有一個對象使用moc.Single()

    編輯:如果ManagementObjectCollection沒有實現IEnumerable<ManagementObject>比上述擴展方法確實沒有實現(這是一樣索引雖然)。你可以手動完成同樣的事情:

    var enumerator = moc.GetEnumerator(); 
    if(!enumerator.MoveNext()) throw new Exception("No elements"); 
    ManagementObject obj = (ManagementObject) enumerator.Current; 
    string stFilePath = obj["ExecutablePath"]; 
    
    +0

    [「Path」]元素呢?像這樣:'moc.First()[「Path」]'? – seebiscuit

    +0

    如果'moc.First()'返回的類型('ManagementObject')支持索引('[]'),那就行了。 – Steve

    +0

    @Grzenio它不起作用。 'moc'不支持索引。這是問題的根源。 – seebiscuit

    相關問題