C#:通过引用将附加参数传递给委托
我目前正试图大量优化程序的运行时,但无意中发现了以下问题 问题 在某些时候,我必须从C#:通过引用将附加参数传递给委托,c#,optimization,delegates,pass-by-reference,C#,Optimization,Delegates,Pass By Reference,我目前正试图大量优化程序的运行时,但无意中发现了以下问题 问题 在某些时候,我必须从user32.dll(请参阅)调用EnumWindows,定义如下: 内部静态类NativeMethods { 公共委托bool EnumWindowsProc(IntPtr hWnd、intlparam); [DllImport(“user32.dll”,SetLastError=true)] [返回:Marshallas(UnmanagedType.Bool)] 公共静态外部bool EnumWindows(
user32.dll
(请参阅)调用EnumWindows
,定义如下:
内部静态类NativeMethods
{
公共委托bool EnumWindowsProc(IntPtr hWnd、intlparam);
[DllImport(“user32.dll”,SetLastError=true)]
[返回:Marshallas(UnmanagedType.Bool)]
公共静态外部bool EnumWindows(EnumWindowsProc enumFunc、IntPtr lParam);
//...
}
正如您所看到的,我传递了一个代理来处理每个窗口
我这样称呼这个方法:
NativeMethods.EnumWindows(GetVisibleWindowDelegate,IntPtr.Zero);
与
private bool GetVisibleWindowDelegate(IntPtr windowHandle,int)
注意:我没有在委托中使用int
参数,因此名称为
这个很好用。现在进行优化:我必须访问和存储多个动态类型列表List
和IDictionary
,它们封装在一个名为RuntimeInformation
的对象中,跨越不同类中的多个方法
从这个RuntimeInformation对象来回复制值会在我的硬件上为每个方法调用使用大约20毫秒的宝贵运行时。这就是为什么我想通过引用传递这个对象,但是我无法将引用获取到我的GetVisibleWindowDelegate
方法
我无法更改委托类型,因为我无法控制调用它
如果我尝试像这样调用EnumWindows
:
NativeMethods.EnumWindows(
(windowHandle,)=>GetVisibleWindowDelegate(windowHandle,ref runtimeInformation),
IntPtr.Zero
);
我得到了错误
Error CS1628 Cannot use ref, out, or in parameter 'runtimeInformation' inside an anonymous method, lambda expression, query expression, or local function
据我所知,引用的类属性不存在
问题
如何将对我的运行时信息的引用
放入我用作委托的函数中?有没有其他方法可以替代这种方法
解决方案应具有高性能(第一优先级)和可维护性。您可以使用它。事实上,我们有一个例子来说明你到底想做什么
private static bool GetVisibleWindowDelegate(IntPtr windowHandle, IntPtr lparam)
{
var handle = GCHandle.FromIntPtr(lparam);
var runtimeInformation = (RuntimeInformation)handle.Target;
// ...
}
RuntimeInformation runtimeInformation = ...
var handle = GCHandle.Alloc(runtimeInformation);
try
{
var callback = new EnumWindowsProc(GetVisibleWindowDelegate);
NativeMethods.EnumWindows(callback, GCHandle.ToIntPtr(handle));
}
finally
{
handle.Free();
}