本文介绍了MulticastDelegate和异常处理:是否有可能把它包起来都统称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当调用多播委托应该使用GetInvocationList一个调用的一个代表:

When calling a Multicast Delegate one should use GetInvocationList to call one by one the delegate:

public void IterateAll()
{
    if( _doExecute != null )
    {
        foreach( ExecuteCallback doSingleExecute in _doExecute.GetInvocationList() )
        {
            try
            {
                doSingleExecute();
            }
            catch
            {
                // This delegate threw an exception
            }
        }
    }
}

有没有办法来泛化这使得通过包装本次迭代,以隐藏它,这样就可以只再次呼吁全播委托回到一个单一的电话吗?这将接近于故意水平

Is there a way to genericize this so as to go back to one single call by wrapping this iteration so as to hide it and so that one could call only once again the whole multicast delegate ? This would be closer to the intentional level.

推荐答案

您可以做这样的事情:

public static void CallAllAndCatch(this Action self)
{
    if (self == null)
        return;

    foreach (Action i in self.GetInvocationList()) {
        try { i(); }
        catch { }
    }
}

请注意,您的可以的使用泛型,如果你发现自己做这个有很多如与事件处理程序< T> ,但不能笼统地对这样做的任何的,因为委托类型类型不能指定任何的委托彼此之间,即使它们是兼容的,并且没有限定一个通用的方法来限制​​特定的通用参数是与特定签名的委托时机构。 (我的认为的委托具有相同签名被认为是兼容的类型开始.NET 4。)

Note that you can use generics if you find yourself doing this a lot with e.g. EventHandler<T>, but you cannot do this generically for any delegate of any type since delegate types cannot be assigned between each other, even if they are compatible, and there is no mechanism when defining a generic method to restrict a specific generic parameter to be a delegate with a specific signature. (I think delegates with identical signatures are considered compatible types starting with .NET 4.)

对于事件处理程序&LT; T&GT; 办法:

public static void CallAllAndCatch(this EventHandler<T> self, object sender, T args)
    where T : EventArgs
{
    if (self == null)
        return;

    foreach (EventHandler<T> i in self.GetInvocationList()) {
        try { i(sender, args); }
        catch { }
    }
}

如果你不介意扔性能和编译时类型检查下来的管子,你可以做到这一点,它可以与任何委托类型:

If you don't mind throwing performance and compile-time type checking down the tube, you can do this, which will work with any delegate type:

public static void CallAllAndCatch(this Delegate self, params object[] args)
    where T : EventArgs
{
    if (self == null)
        return;

    foreach (Delegate i in self.GetInvocationList()) {
        try { i.DynamicInvoke(args); }
        catch (MemberAccessException) { throw; } // A type of something in args isn't compatible with the delegate signature.
        catch (TargetException) { throw; } // The delegate itself is invalid.
        catch { } // Catch everything else.
    }
}

这篇关于MulticastDelegate和异常处理:是否有可能把它包起来都统称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 18:31