在 .Net 2.0 的 Property 的 getter 中不使用 Func 进行调用
我想在 getter 中使用 Invoke,当使用 .Net 2.0 而不是 4.0 时该怎么做?对于.Net> 2.0 我们可以使用 Func
.Net 2.0 的替代品是什么?
以下是 .Net 4.0 的示例(来自 链接)
public ApplicationViewModel SelectedApplication
{
get {
if (this.InvokeRequired)
{
return (ApplicationViewModel)this.Invoke(new Func<ApplicationViewModel>(() => this.SelectedApplication));
}
else
{
return _applicationsCombobox.SelectedItem as ApplicationViewModel;
}
}
}
I would like to use Invoke in getter, how to do it when using .Net 2.0 not e.g. 4.0? For .Net > 2.0 we can use Func
and what is replacement for .Net 2.0?
Here is example for .Net 4.0 (from link)
public ApplicationViewModel SelectedApplication
{
get {
if (this.InvokeRequired)
{
return (ApplicationViewModel)this.Invoke(new Func<ApplicationViewModel>(() => this.SelectedApplication));
}
else
{
return _applicationsCombobox.SelectedItem as ApplicationViewModel;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您使用的是 .NET 2.0,因此您将无法使用
Func
委托,但您可以使用 MethodInvoker 委托。您将无法在 .NET 2.0 中使用 lambda 表达式语法,但可以使用“匿名委托”语法(几乎是同一件事),如下面的代码示例所示。
从非 UI 线程查询 UI 控件中的数据通常是一件不常见的事情;通常,您的 UI 控件会触发在 UI 线程上执行的事件,因此您当时可以从 UI 控件中收集所需的数据,然后将该数据传递给其他函数,因此您无需担心执行 Invoke 。
不过,在您的情况下,您应该能够执行以下操作:
编辑:现在我查看了您的 .NET 4.0 代码示例并查看了 Invoke 函数,我看到它如何返回一个值(不是我认为的)以前有过使用的理由)。
好吧,MethodInvoker 委托不需要返回值,但正如 @haiyyu 指出的,您可以定义自己的委托。例如,您只需要定义自己的
Func
委托,原始代码可能会正常工作:来自 MSDN 页面的示例代码:
Since you're using .NET 2.0, you won't have the
Func
delegate available to you, but you can use the MethodInvoker delegate.You won't be able to use the lambda expression syntax with .NET 2.0, but you can use the "anonymous delegate" syntax (which is pretty much the same thing), as shown in the code example below.
Querying data in UI controls from a non-UI thread is generally an uncommon thing to do; usually your UI controls trigger events that execute on the UI thread, so you gather the data you need from your UI controls at that time and then pass that data on to some other function, so you don't need to worry about doing an Invoke.
In your case, though, you should be able to do something like this:
EDIT: Now that I look at your .NET 4.0 code sample and also look at the Invoke function, I see how it can return a value (not something that I've had a reason to use before).
Well, the MethodInvoker delegate does not expect a return value, but as @haiyyu pointed out, you could define your own delegate. For instance, you would just need to define your own
Func<TResult>
delegate, and the original code would probably work fine:Sample code from the MSDN page:
使用委托,它们是一种类型化函数指针。
以下是更多阅读内容:http://msdn。 microsoft.com/en-us/library/ms173171%28v=vs.80%29.aspx
Use delegates, they are a sort of typed function pointers.
Here's some more reading: http://msdn.microsoft.com/en-us/library/ms173171%28v=vs.80%29.aspx