委托有ref参数 [英] Delegate with ref parameter

查看:304
本文介绍了委托有ref参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法来维持在code以下相同的功能,但无需创建委托?我的接口与一个包含许多不同的DeleteSomethingX(参考IntPtr的PTR)方法的第三方API和我想集中在code为IntPtr.Zero检查。

 私人无效委托CleanupDelegate(参考IntPtr的PTR);

...

私人无效清理(参考IntPtr的PTR,CleanupDelegate清理)
{
    如果(PTR!= IntPtr.Zero)
    {
        清理(​​REF PTR);
    }
}
 

解决方案

如果你的意思是不宣的委托类型,则可能不会;很少(如果有的话)内置代表使用 REF ;但你可以把通用的:

 委托无效ActionRef< T>(REF的T值);
 

我不知道这节省了很多,虽然。有可能的的是一些技巧,这里的扩展方法,但很难说没有更多的细节。

Is there any way to maintain the same functionality in the code below, but without having to create the delegate? I'm interfacing with a 3rd-party API that contains a number of various DeleteSomethingX(ref IntPtr ptr) methods and I'm trying to centralize the code for the IntPtr.Zero check.

private void delegate CleanupDelegate(ref IntPtr ptr);

...

private void Cleanup(ref IntPtr ptr, CleanupDelegate cleanup)
{
    if (ptr != IntPtr.Zero)
    {
        cleanup(ref ptr);
    }
}

解决方案

If you mean without declaring the delegate type, then probably not; very few (if any) inbuilt delegates use ref; but you could make it generic:

delegate void ActionRef<T>(ref T value);

I'm not sure this saves much though. There may also be some tricks here with extension methods, but it is hard to tell without more detail.

这篇关于委托有ref参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆