下面哪个代码更实用、可行、速度更快? C#
这两种方法都可以正常工作,但我想知道哪一个“更好”?要么是最佳实践,要么更少出现错误,要么更快?
方法1:
public static ListViewItem[] GetProcessData()
{
ManagementClass MgmtClass = new ManagementClass("Win32_Process");
ListViewItem[] ProcessItems = new ListViewItem[MgmtClass.GetInstances().Count - 2];
int i = 0;
foreach (ManagementObject Processes in MgmtClass.GetInstances())
{
if (!Processes["Name"].ToString().ToLower().Contains("system"))
{
string[] ProcessInfo = { Processes["Name"].ToString(), Processes["ProcessId"].ToString() };
ProcessItems[i] = new ListViewItem(ProcessInfo);
i++;
}
}
return ProcessItems;
}
方法2:
public static ListViewItem[] GetProcessData()
{
Process[] PInfo = Process.GetProcesses();
ListViewItem[] ProcessItems = new ListViewItem[PInfo.Length - 2];
int j = 0;
for (int i = 0; i < PInfo.Length; i++)
{
if (!PInfo[i].ProcessName.ToLower().Contains("system") & !PInfo[i].ProcessName.ToLower().Contains("idle"))
{
string[] ProcessInfo = { PInfo[i].MainModule.ModuleName, PInfo[i].Id.ToString() };
ProcessItems[j] = new ListViewItem(ProcessInfo);
j++;
}
}
return ProcessItems;
}
Both of these methods work correctly, but I was wondering which of them is "better"? Either best practices, less bug prone or faster?
Method 1:
public static ListViewItem[] GetProcessData()
{
ManagementClass MgmtClass = new ManagementClass("Win32_Process");
ListViewItem[] ProcessItems = new ListViewItem[MgmtClass.GetInstances().Count - 2];
int i = 0;
foreach (ManagementObject Processes in MgmtClass.GetInstances())
{
if (!Processes["Name"].ToString().ToLower().Contains("system"))
{
string[] ProcessInfo = { Processes["Name"].ToString(), Processes["ProcessId"].ToString() };
ProcessItems[i] = new ListViewItem(ProcessInfo);
i++;
}
}
return ProcessItems;
}
Method 2:
public static ListViewItem[] GetProcessData()
{
Process[] PInfo = Process.GetProcesses();
ListViewItem[] ProcessItems = new ListViewItem[PInfo.Length - 2];
int j = 0;
for (int i = 0; i < PInfo.Length; i++)
{
if (!PInfo[i].ProcessName.ToLower().Contains("system") & !PInfo[i].ProcessName.ToLower().Contains("idle"))
{
string[] ProcessInfo = { PInfo[i].MainModule.ModuleName, PInfo[i].Id.ToString() };
ProcessItems[j] = new ListViewItem(ProcessInfo);
j++;
}
}
return ProcessItems;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会使用 Process 类作为类型化方法。在这种情况下,不太容易出现错误:
I would use Process class as a typed approach. A little less bug prone in this case: