开发者

How to make Action<param,param2> compatible with event's delegate type?

开发者 https://www.devze.com 2022-12-08 11:28 出处:网络
Given the code below: void LookupBox_Load(object sender, EventArgs e) { Action d = delegate { if (!_p.AutoClose)

Given the code below:

void LookupBox_Load(object sender, EventArgs e)
{
    Action d = delegate
        {
            if (!_p.AutoClose)
                CloseLookupBox();
        };

    if开发者_如何学JAVA (this.ParentForm.MdiParent != null)
        this.ParentForm.MdiParent.Deactivate += delegate { d(); };
    else
        this.ParentForm.Deactivate += delegate { d(); };
}

Is there a way to omit the delegate { d(); } ?

void LookupBox_Load(object sender, EventArgs e)
{
    Action<object,EventArgs> d = delegate
        {
            if (!_p.AutoClose)
                CloseLookupBox();
        };

    if (this.ParentForm.MdiParent != null)
        this.ParentForm.MdiParent.Deactivate += d;
    else
        this.ParentForm.Deactivate += d;
}

Note: I want to do this inline


Absolutely - change the type of d to start with:

EventHandler d = delegate
    {
        if (!_p.AutoClose)
            CloseLookupBox();
    };

Anonymous methods don't just work with Func and Action...

For future reference though, you can create a new delegate based on an existing one with a compatible signature:

Action<object, EventArgs> d = ...;
EventHandler handler = new EventHandler(d);

But this extra indirection is pointless in this case :)

You can also make the code calling it slightly simpler too using the null-coalescing operator:

Form form = ParentForm.MdiParent ?? ParentForm;
form.Deactivate += d;

As you're then only using d once, you could inline it, turning the whole method into:

Form form = ParentForm.MdiParent ?? ParentForm;
form.Deactivate += delegate
{
    if (!_p.AutoClose)
        CloseLookupBox();
};


Not much better, but you could do if you're using C# 3.0:

if (this.ParentForm.MdiParent != null)
    this.ParentForm.MdiParent.Deactivate += (x,y) => d();
else
    this.ParentForm.Deactivate += (x,y) => d();


You should use EventHandler<MyEventArgs> to define those instead of the Action delegate

  EventHandler<EventArgs> d = delegate        
       {            
            if (!_p.AutoClose)                
               CloseLookupBox();        
       };    
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号