C#循环遍历声明类内的每个事件

3
我在某个地方看到过这样的代码。
理想情况下,我希望像这样的循环能够适应这个 Func 事件类型。
public static event Func<RecentDirectories, DirectoryInfo, Exception, bool> ContinueOnExceptionEvent;

/// <summary>
/// Determine if the loop should continue on a general exception not already handled
/// in the loop's catch statement.
/// </summary>
/// <param name="dir"></param>
/// <param name="e"></param>
/// <returns>True continues loop, false rethrows the exception</returns>
protected virtual bool TryContinueOnException(DirectoryInfo dir, Exception ex)
{
    if (!Aborted) // check if thread aborted before doing event
    {
        if (null != ContinueOnExceptionEvent)
        {
            // foreach line doesn't compile because 
            // ContinueOnExceptionEvent doesn't have a GetEnumerator()
            foreach (var e in ContinueOnExceptionEvent)
            {
                if (e(this, dir, ex))
                {
                    return true;
                }
            }
        }
    }

    return false;
}

如何使用foreach获取所有事件并对它们进行迭代?

1个回答

2
您可以通过调用GetInvocationList来访问每个订阅者。
protected virtual bool TryContinueOnException(DirectoryInfo dir, Exception ex)
{
    if (!Aborted)
    {
        var e = ContinueOnExceptionEvent;
        if (e != null)
        {
            var ds = e.GetInvocationList();
            foreach (Func<RecentDirectories, DirectoryInfo, Exception, bool> d in ds)
            {
                if (d(this, dir, ex))
                    return true;
            }
        }
    }
    return false;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接