2016-07-09 23 views
3

所以,我有這樣的代碼方式來設置屬性取決於其他財產

 Process[] processesManager = Process.GetProcesses(); 
     List<ProcessInfo> temporaryProcessesList = new List<ProcessInfo>(); 
     for (int i = 0; i < processesManager.Length; ++i) 
     { 
      temporaryProcessesList.Add(new ProcessInfo(processesManager[i].ProcessName, processesManager[i].Id, TimeSpan.Zero, "Group")); 
     } 

     processesList = temporaryProcessesList.GroupBy(d => new {d.Name}).Select(d => d.First()).ToList(); 

此代碼是用於獲取當前進程。然後我將這些處理加入temporaryProcessesList。而不是簡單的字符串「組」我想根據進程的名稱來設置屬性。例如,如果進程名爲leagueoflegends.exe,那麼我想將組設置爲「遊戲」,如果它的devenv.exe我想將組設置爲「軟件開發」。

而我的問題是,如何做到最簡單/最好的方式?我正在考慮使用帶字符串和枚舉的字典。並將ProcessName與字符串進行比較。但也許有更好的方法來做到這一點。

ProcessInfo是具有4個屬性和構造函數的簡單類。

public class ProcessInfo 
{ 
    private string Name { get; set; } 
    private int Id { get; set; } 
    private TimeSpan Time { get; set; } 
    private string Group { get; set; } 

    public ProcessInfo(string name, int id, TimeSpan time, string group) 
    { 
     Name = name; 
     Id = id; 
     Time = time; 
     Group = group; 
    } 
} 

回答

1

也許這是你在找什麼:

public class ProcessInfo 
{ 
    private string _name; 
    private string Name 
    { 
     get { return _name; } 
     set 
     { 
      _name = value; 
      UpdateGroupName(); 
     } 
    } 
    private int Id { get; set; } 
    private TimeSpan Time { get; set; } 
    private string Group { get; set; } 

    private void UpdateGroupName() 
    { 
     Group = ProcessNames::GetGroupFromProcessName(Name); 
    } 

    public ProcessInfo(string name, int id, TimeSpan time) 
    { 
     Name = name; 
     Id = id; 
     Time = time; 
    } 
} 

internal static class ProcessNames 
{ 
    private static Dictionary<string, string> _names; 

    public static string GetGroupNameFromProcessName(string name) 
    { 
     // Make sure to add locking if there is a possibility of using 
     // this from multiple threads. 
     if(_names == null) 
     { 
      // Load dictionary from JSON file 
     } 

     // Return the value from the Dictionary here, if it exists. 
    } 
} 

這種設計並不完美,但希望你看到這個想法。您也可以將Group名稱的更新移動到構造函數中,但如果在構建後設置屬性,則不會更改Group名稱。

此外,您可以使用INotifyPropertyChanged和/或依賴注入來清理接口。 https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx

+0

它比寫字典更像書寫方式,因爲我需要爲每個過程編寫案例。但是,那是另一個解決方案。 – Porqqq

+0

確實如此,但您可以更新'UpdateGroupName'方法以從文本文件,XML文件等中讀取進程名稱及其對應的組名。這樣,您就可以在不重建的情況下更新組名。 –

+0

Hymm ..我想用字典來做。我的意思是從json文件讀到字典,我認爲這會是更好的方法。你不覺得嗎? – Porqqq

3

使用字典是實現這一目標的最佳方式:

var dictionary = new Dictionary<string, string>(); 
dictionary.Add("a.exe", "aGroup"); 
dictionary.Add("b.exe", "bGroup"); 

string val; 
if (dictionary.TryGetValue(processName, out val)) 
    processInfo.Group = val; 
else 
    processInfo.Group = "Undefined Group"; 
+0

感謝您的回答。但也許有人會知道一些其他方式來做到這一點。 – Porqqq

相關問題