2012-02-22 25 views
0

我想在getter中使用Invoke,在使用.Net 2.0时不要使用Invoke。 4.0?对于.Net> 2.0,我们可以使用Func以及.Net 2.0的替代品是什么?在属性的getter中为.Net 2.0调用没有Func

这里是例如用于.NET 4.0(从link

public ApplicationViewModel SelectedApplication 
{ 
    get { 
      if (this.InvokeRequired) 
      { 
       return (ApplicationViewModel)this.Invoke(new Func<ApplicationViewModel>(() => this.SelectedApplication)); 
      } 
      else 
      { 
       return _applicationsCombobox.SelectedItem as ApplicationViewModel; 
      } 
     } 
} 
+0

你可以创建自己的委托。 – haiyyu 2012-02-22 14:40:02

回答

2

由于您使用.NET 2.0,你会不会有Func委托提供给你,但你可以使用MethodInvoker委托。

您将无法在.NET 2.0中使用lambda表达式语法,但您可以使用“匿名委托”语法(几乎相同的事情),如下面的代码示例所示。

从非UI线程查询UI控件中的数据通常是不常见的事情;通常你的UI控件触发在UI线程上执行的事件,所以你在那时从你的UI控件收集你需要的数据,然后将这些数据传递给其他函数,所以你不需要担心做一个Invoke 。

在你的情况,但是,你应该能够做这样的事情:

public ApplicationViewModel SelectedApplication 
{ 
    get 
    { 
     if (this.InvokeRequired) 
     { 
      ApplicationViewModel value = null; // compiler requires that we initialize this variable 
      // the call to Invoke will block until the anonymous delegate has finished executing. 
      this.Invoke((MethodInvoker)delegate 
      { 
       // anonymous delegate executing on UI thread due calling the Invoke method 
       // assign the result to the value variable so that we can return it. 
       value = _applicationsCombobox.SelectedItem as ApplicationViewModel; 
      }); 
      return value; 
     } 
     else 
     { 
      return _applicationsCombobox.SelectedItem as ApplicationViewModel; 
     } 
    } 
} 

编辑:现在,我看看你的.NET 4.0的代码示例,也看调用函数,我看它如何返回一个值(不是我以前有理由使用的东西)。

那么,MethodInvoker委托并不期望返回值,但@haiyyu指出,您可以定义自己的委托。举例来说,你只需要定义自己的Func<TResult>委托,和原来的代码可能会很好地工作:从MSDN页面

// this is all that is required to declare your own Func<TResult> delegate. 
delegate TResult Func<TResult>(); 

示例代码:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     // Create a timer that will call the ShowTime method every second. 
     var timer = new System.Threading.Timer(ShowTime, null, 0, 1000);   
    } 

    private void ShowTime(object x) 
    { 
     // Don't do anything if the form's handle hasn't been created 
     // or the form has been disposed. 
     if (!this.IsHandleCreated && !this.IsDisposed) return; 

     // Invoke an anonymous method on the thread of the form. 
     this.Invoke((MethodInvoker) delegate 
     { 
      // Show the current time in the form's title bar. 
      this.Text = DateTime.Now.ToLongTimeString(); 
     }); 
    } 
} 
+0

很好的答案,谢谢! – jotbek 2012-02-22 15:20:25

相关问题