C#循环声明类内部的每个事件
我在某个地方见过这样的代码 理想情况下,我希望这样一个循环来适应这个Func事件类型C#循环声明类内部的每个事件,c#,exception-handling,C#,Exception Handling,我在某个地方见过这样的代码 理想情况下,我希望这样一个循环来适应这个Func事件类型 public static event Func<RecentDirectories, DirectoryInfo, Exception, bool> ContinueOnExceptionEvent; /// <summary> /// Determine if the loop should continue on a general exception not already h
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;
}
公共静态事件函数ContinueOnExceptionEvent;
///
///确定循环是否应在尚未处理的常规异常上继续
///在循环的catch语句中。
///
///
///
///True继续循环,false重新引发异常
受保护的虚拟bool TryContinueOnException(DirectoryInfo dir,Exception ex)
{
if(!Aborted)//在执行事件之前检查线程是否已中止
{
if(null!=ContinueOnExceptionEvent)
{
//foreach行不编译,因为
//ContinueOnExceptionEvent没有GetEnumerator()
foreach(ContinueOnExceptionEvent中的变量e)
{
if(e(本部、本部、本部))
{
返回true;
}
}
}
}
返回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;
}
受保护的虚拟bool TryContinueOnException(DirectoryInfo dir,Exception ex)
{
如果(!中止)
{
var e=持续例外事件;
如果(e!=null)
{
var ds=e.GetInvocationList();
foreach(ds中的函数d)
{
if(d(本部、本部、本部))
返回true;
}
}
}
返回false;
}