什么是此lambda表达式的C#2.0等效代码

时间:2012-02-23 14:48:18

标签: lambda c#-3.0 c#-2.0

我需要一个通过打开资源管理器窗口枚举的功能。这是我得到的代码:

delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam);

[DllImport("user32.dll")]
static extern bool EnumThreadWindows(int dwThreadId, EnumThreadDelegate lpfn, IntPtr lParam);

static IEnumerable<IntPtr> EnumerateProcessWindowHandles(int processID)
{
    List<IntPtr> handles = new List<IntPtr>();

    foreach (ProcessThread thread in Process.GetProcessById(processID).Threads)
    {                                //what is the magic going on beneath this?? :o
        EnumThreadWindows(thread.Id, (hWnd, lParam) => { handles.Add(hWnd); return true;}, IntPtr.Zero);
    }
    return handles;
}

代码继续这样:

[DllImport("coredll.dll")]
static extern int ShowWindow(IntPtr hWnd, int nCmdShow);

const int SW_MINIMIZED = 6;

private void button1_Click(object sender, EventArgs e)
{
    foreach (IntPtr handle in EnumerateProcessWindowHandles(Process.GetProcessesByName("explorer")[0].Id))
    {
        ShowWindow(handle, SW_MINIMIZED);
    }
}

我的问题是,在第一个代码块中,如何替换lambda表达式,以便我可以在VS 2005中使用C#2.0编译代码。

2 个答案:

答案 0 :(得分:2)

创建一个新方法,像这样传递到EnumThreadWindows

static bool EnumThreadCallback(IntPtr hWnd, IntPtr lParam)
{
    // Close the enumerated window.
    PostMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);

    return true;
}

让代表同意:

public delegate bool EnumThreadDelegate (IntPtr hWnd, IntPtr lParam);

然后调用这个函数:

foreach (ProcessThread pt in proc.Threads)
{
    EnumThreadWindows((uint)pt.Id, new EnumThreadDelegate(EnumThreadCallback), IntPtr.Zero); 
}

来源:http://www.pinvoke.net/default.aspx/user32/EnumThreadWindows.html

答案 1 :(得分:1)

delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam);

static IEnumerable<IntPtr> EnumerateProcessWindowHandles(int processID)
{
    List<IntPtr> handles = new List<IntPtr>();

    EnumThreadDelegate addWindowHandle = delegate(IntPtr hWnd, IntPtr param)
    {
        handles.Add(hWnd); 
        return true;
    };

    foreach (ProcessThread thread in Process.GetProcessById(processID).Threads)
    {
        EnumThreadWindows(thread.Id, addWindowHandle, IntPtr.Zero);
    }
    return handles;
}