我发现了一个只能使用委托的特殊用例:
public delegate bool WndEnumProc(IntPtr hwnd, IntPtr lParam);
[DllImport("User32.dll")]
public static extern bool EnumWindows(WndEnumProc lpEnumFunc, IntPtr lParam);
使用 Func/Action 不起作用'Namespace.Class.WndEnumProc' is a 'field' but is used like a 'type'
::
public Func<IntPtr, IntPtr, bool> WndEnumProc;
[DllImport("User32.dll")]
public static extern bool EnumWindows(WndEnumProc lpEnumFunc, IntPtr lParam);
以下代码确实可以编译,但在运行时抛出异常,因为System.Runtime.InteropServices.DllImportAttribute
不支持泛型类型的编组:
[DllImport("User32.dll")]
public static extern bool EnumWindows(Func<IntPtr, IntPtr, bool> lpEnumFunc, IntPtr lParam);
我举这个例子是为了向大家展示:有时委托是你唯一的选择。这是对您问题的合理回答why not use Action<T>/Func<T> ?