1

鉴于以下代码:

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

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

有没有办法省略委托 { 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;
}

注意:我想内联

4

3 回答 3

4

绝对 - 更改d开头的类型:

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

匿名方法不仅适用于 Func 和 Action...

不过,为了将来参考,您可以基于具有兼容签名的现有委托创建一个新委托:

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

但是在这种情况下,这种额外的间接是没有意义的:)

您还可以使用 null-coalescing 运算符使调用它的代码稍微简单一些:

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

因为你只使用d一次,你可以内联它,把整个方法变成:

Form form = ParentForm.MdiParent ?? ParentForm;
form.Deactivate += delegate
{
    if (!_p.AutoClose)
        CloseLookupBox();
};
于 2009-10-16T06:33:51.353 回答
2

也好不到哪里去,但如果您使用 C# 3.0,您可以这样做:

if (this.ParentForm.MdiParent != null)
    this.ParentForm.MdiParent.Deactivate += (x,y) => d();
else
    this.ParentForm.Deactivate += (x,y) => d();
于 2009-10-16T06:26:59.407 回答
0

您应该使用EventHandler<MyEventArgs>来定义那些而不是 Action 委托

  EventHandler<EventArgs> d = delegate        
       {            
            if (!_p.AutoClose)                
               CloseLookupBox();        
       };    
于 2009-10-16T06:30:38.130 回答