Func<EventHandler, get property value from args?
Have tried to solve this for quite a while now, but without luck... My idea was to have some sort of a configuration for different settings, for instance.. controlling how exceptions are handled.
Some of my code :)
public class ErrorEventArgs : EventArgs
{
public bool Handled { get; set; }
...
...
}
A property in my main class like :
EventHandler<ErrorEventArgs> ErrorConfiguration {get; set;}
I then have an OnError where I need to know value of Handled,
internal void OnError(ErrorEventArgs args)
{
Func<EventHandler<ErrorEventArgs>, bool> IsHandled;
IsHandled = ev => ??? // invoke ErrorConfiguration?
if (ErrorConfiguration != null && IsHandled(E开发者_C百科rrorConfiguration ))
error(this, args);
}
How can this be solved?
I can do like this, if it's the EventHandler without the Func, but I want to encapsulate the boolean expression. Why cant I chain the lambda... :(
EventHandler<ErrorEventArgs> IsHandled;
IsHandled = (sender, e) => e.ErrorContext.Handled;
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);
You really don't need any lambda to call your just need to call your delegate directly:
internal void OnError(ErrorEventArgs args)
{
if (ErrorConfiguration != null)
ErrorConfiguration(this, args);
if (args.Handled)
error(this, args);
}
If you want to the use the same thing in a lambda, you'll have do to this, which will take more lines of code:
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);
}
精彩评论