如何使 Action与事件的委托类型兼容吗?
给出下面的代码:
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(); };
}
有没有办法省略 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;
}
注意:我想内联执行此操作
Given the code below:
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(); };
}
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
绝对 - 更改
d
的类型以开始:匿名方法不仅仅适用于 Func 和 Action...
为了将来的参考,您可以创建一个新的委托基于具有兼容签名的现有代码:
但是在这种情况下,这种额外的间接寻址是没有意义的:)
您还可以使用空合并运算符使调用它的代码也稍微简单一些:
因为您只使用
d
一次,您可以内联它,将整个方法变成:Absolutely - change the type of
d
to start with: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:
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:
As you're then only using
d
once, you could inline it, turning the whole method into:好不了多少,但如果您使用 C# 3.0,您可以这样做:
Not much better, but you could do if you're using C# 3.0:
您应该使用 EventHandler 来定义这些而不是 Action代表
You should use EventHandler<MyEventArgs> to define those instead of the Action delegate