gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:17:40 32 4
gpt4 key购买 nike

我在某处看到过这样的代码。

理想情况下,我想要一个像这样的循环来适应这种 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 获取所有事件并对它们进行迭代?

最佳答案

您可以通过调用 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;
}

关于C# 循环声明类内部的每个事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6297216/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com