所以,我有这段代码
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
。而不是简单的字符串“Group”,我想根据进程的名称设置属性。例如,如果进程的名称为 leagueoflegends.exe,那么我想将组设置为“游戏”,如果它的 devenv.exe 我想将组设置为“软件开发”。
我的问题是,如何以最简单/最好的方式做到这一点?我正在考虑将 Dictionary 与字符串和枚举一起使用。并将 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;
}
}
最佳答案
使用字典是实现此目的的最佳方式:
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";
关于c# - 根据其他属性设置属性的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38284302/