English 中文(简体)
• 如何采取行动 符合活动代表类型?
原标题:How to make Action<param,param2> compatible with event s delegate type?
  • 时间:2009-10-16 06:23:36
  •  标签:

考虑到以下法典:

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;
}

注:我想按此行。

最佳回答

绝对——将<代码>d的类型改为:

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

匿名方法不只与Func和“行动”合作......

在未来参考中,您can<>>>/em>根据现有拥有兼容签名的代表情况,设立了一个新的代表:

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

但是,在这种情况下,这种间接的间接性是毫无意义的:

您也可以使用无编码操作者,使其略为简单:

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

既然你只使用<代码>d,你可以把整个方法改为:

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

不太好,但如果你重新使用C#3.0的话,你可以这样做:

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

页: 1 活动Handler<MyEventArgs>,以界定这些内容而不是行动代表。

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




相关问题