有没有办法可以将函数内联到 Action 委托并同时引用它?
有没有办法可以内联委托任务而不是将其分离到另一个函数上?
原始代码:
private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
{
System.Threading.ThreadPool.QueueUserWorkItem((o) => Attach());
}
void Attach() // I want to inline this function on FileOk event
{
if (this.InvokeRequired)
{
this.Invoke(new Action(Attach));
}
else
{
// attaching routine here
}
}
我希望它是这样的(不需要创建单独的函数):
private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
{
Action attach = delegate
{
if (this.InvokeRequired)
{
// but it has compilation here
// "Use of unassigned local variable 'attach'"
this.Invoke(new Action(attach));
}
else
{
// attaching routine here
}
};
System.Threading.ThreadPool.QueueUserWorkItem((o) => attach());
}
Is there a way I can inline the delegated task instead of separating it on another function?
Original Code:
private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
{
System.Threading.ThreadPool.QueueUserWorkItem((o) => Attach());
}
void Attach() // I want to inline this function on FileOk event
{
if (this.InvokeRequired)
{
this.Invoke(new Action(Attach));
}
else
{
// attaching routine here
}
}
I wanted it to be like this(no need to create a separate function):
private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
{
Action attach = delegate
{
if (this.InvokeRequired)
{
// but it has compilation here
// "Use of unassigned local variable 'attach'"
this.Invoke(new Action(attach));
}
else
{
// attaching routine here
}
};
System.Threading.ThreadPool.QueueUserWorkItem((o) => attach());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
出现“使用未分配的变量”错误的原因是编译器实际生成代码的方式。 当您使用 delegate{} 语法时,编译器会为您创建一个真正的方法。 由于您在委托中引用附加字段,编译器会尝试将局部变量
attach
传递给生成的委托方法。下面是粗略翻译的代码,应该有助于使其更清晰:
请注意,它在初始化之前将附加字段传递给 _b<>_1 方法。
The reason you get the "use of unassigned variable" error is because of the way the compiler actually generates the code. When you use the delegate{} syntax a real method is created for you by the compiler. Since you're referencing the attached field in your delegate, the compiler attempts to pass the local variable
attach
to the generated delegate method.Here's the roughly translated code which should help make it clearer:
Notice that it's passing the attach field to the _b<>_1 method before it's initialized.
我认为这会起作用:
您需要做的就是在声明匿名方法的行之前为“attach”分配一个值(null 有效)。 我确实认为前者更容易理解。
I think this will work:
All you need to do is assign a value to 'attach' (null works) before the line that declares the anonymous method. I do think the former is a bit easier to understand though.