单独调用代表? [英] Calling delegates individually?

查看:112
本文介绍了单独调用代表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有像这样的委托:

 委托无效渲染(); 
渲染ToRender;



在这里使用它:

  ToRender + = FunctionRender; 
ToRender + = SomeOtherRender;



我怎样才能使它这样我就可以单独调用每个功能?事情是这样的:

 的foreach(渲染ToRender渲染)
{
BeginRender();


渲染();


EndRender();
}


解决方案

您可以分别获取每一个使用 Delegate.GetInvocationList()

 的foreach(渲染渲染ToRender.GetInvocationList())
$ { b $ b ...
}

注意 GetInvocationList( )刚刚返回委派[] ,但的foreach 对每个项目隐式转换,这是什么使上述循环的工作。



哦,你应该检查是否 ToRender 或不首先当然是 - 否则,你会得到一个的NullReferenceException 。其实你可以写一个通用的扩展方法,使这个更好,但你需要对未在C#中允许的委托类型约束:(



如果您不关心,缺乏约束,你可以假的:

 公共静态的IEnumerable< T> GetIndividualDelegates< T>(这件T multiDelegate)
,其中T:类
{
如果(multiDelegate == NULL)
{
产量突破;
}
代表D =(代表)(对象)multiDelegate;
的foreach(在d.GetInvocationList委托项目())
{
收益回报(T)(对象)项目;
$} b $ b}

(这是尴尬,因为在通用转换的限制。)



这样,你可以写:

 的foreach(渲染渲染ToRender.GetIndividualDelegates() )
{

}

无需担心是否 ToRender 是空或不是。


if I have a delegate like so:

 Delegate void Render();
 Render ToRender;

And use it here:

 ToRender += FunctionRender;
 ToRender += SomeOtherRender;

How can I make it so I can invoke each function seperately? Something like this:

 foreach(Render render in ToRender)
 {
     BeginRender();


     render();


     EndRender();
 }

解决方案

You can fetch each one separately using Delegate.GetInvocationList().

foreach (Render render in ToRender.GetInvocationList())
{
    ...
}

Note that GetInvocationList() just returns a Delegate[], but foreach has an implicit cast on each item, which is what makes the above loop work.

Oh, and you should check whether ToRender is null or not first, of course - otherwise you'll get a NullReferenceException. You could actually write a generic extension method to make this nicer, but you'd need a constraint on the delegate type which isn't allowed in C# :(

If you don't care about the lack of constraints, you could fake it:

public static IEnumerable<T> GetIndividualDelegates<T>(this T multiDelegate)
    where T : class
{
    if (multiDelegate == null)
    {
        yield break;
    }
    Delegate d = (Delegate)(object) multiDelegate;
    foreach (Delegate item in d.GetInvocationList())
    {
         yield return (T)(object) item;
    }    
}

(It's awkward because of the restrictions on generic conversions.)

That way you could write:

foreach (Render render in ToRender.GetIndividualDelegates())
{
    ...
}

without worrying about whether ToRender was null or not.

这篇关于单独调用代表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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