以下哪些代码更实用,更实用,更快捷? C#

时间:2011-05-23 02:15:28

标签: c# winapi api compare

这两种方法都能正常工作,但我想知道哪些方法“更好”?最佳实践,更少漏洞或更快?

方法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;
    }

1 个答案:

答案 0 :(得分:2)

我会使用Process类作为类型化方法。在这种情况下,更容易出错:

public static ListViewItem[] GetProcessData()
{
    return Process.GetProcesses()
        .Where(arg => arg.Id != 0 && !arg.ProcessName.ToLower().Contains("system"))
        .Select(arg => new ListViewItem(new[] { arg.MainModule.ModuleName, arg.Id.ToString() }))
        .ToArray();
}