1

已经尝试解决这个问题很长一段时间了,但没有运气......我的想法是为不同的设置进行某种配置,例如......控制异常的处理方式。

我的一些代码:)

public class ErrorEventArgs : EventArgs
{
   public bool Handled { get; set; }
...
...
}

我的主要课程中的一个属性,例如:

EventHandler<ErrorEventArgs> ErrorConfiguration {get; set;}

然后我有一个 OnError,我需要知道 Handled 的值,

internal void OnError(ErrorEventArgs args)
{
   Func<EventHandler<ErrorEventArgs>, bool> IsHandled;

   IsHandled = ev => ??? // invoke ErrorConfiguration?

   if (ErrorConfiguration != null && IsHandled(ErrorConfiguration ))
                error(this, args);
}

如何解决?

我可以这样做,如果它是没有 Func 的 EventHandler,但我想封装布尔表达式。为什么我不能链接 lambda... :(

EventHandler<ErrorEventArgs> IsHandled;
IsHandled = (sender, e) => e.ErrorContext.Handled;

我不完全确定你想要达到什么目标。但是您可以执行以下操作:

IsHandled = ev => { ev(this, args); return args.Handled; };

即使我不确定这是否更具可读性、更快、更清洁或类似的东西。我会选择类似的东西

if (ErrorConfiguration != null) ErrorConfiguration(this, args);
if (!args.Handled) error(this, args);
4

2 回答 2

2

I am not completely sure what you want to achieve, exactly. But you can do something like:

IsHandled = ev => { ev(this, args); return args.Handled; };

Even though I am not sure this is more readable, faster, cleaner, or anything like that. I would just go with something like

if (ErrorConfiguration != null) ErrorConfiguration(this, args);
if (!args.Handled) error(this, args);
于 2011-03-19T13:31:11.297 回答
1

你真的不需要任何 lambda 来调用你只需要直接调用你的委托:

internal void OnError(ErrorEventArgs args)
{
   if (ErrorConfiguration != null)
       ErrorConfiguration(this, args);

   if (args.Handled)
       error(this, args);
}

如果你想在 lambda 中使用相同的东西,你必须这样做,这将需要更多的代码行:

internal void OnError(ErrorEventArgs args) {   
Func<EventHandler<ErrorEventArgs>, bool> IsHandled;

   IsHandled = ev => {
        ErrorConfiguration(this, ev);
        return ev.Handled;   
   };

   if (ErrorConfiguration != null && IsHandled(ErrorConfiguration ))
       error(this, args); 
}
于 2011-03-19T13:31:40.333 回答