2012-02-22 4 views
0

getter에서 Invoke를 사용하고 싶습니다. 4.0? .Net 2.0의 경우 Func을 사용할 수 있으며 .Net 2.0의 대체품은 무엇입니까? 여기.Net 2.0에 대한 속성의 getter에서 Func없이 호출

이 (link)에서 닷넷 4.0에 대한 예를

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

을 당신은 당신의 자신의 대리자를 만들 수 있습니다. – haiyyu

답변

2

, 당신은 당신에게 Func 위임을 사용할 필요가 없습니다,하지만 당신은 MethodInvoker 대리자를 사용할 수 있습니다 여기에 좀 더 읽기입니다.

.NET 2.0에서는 람다 식 구문을 사용할 수 없지만 아래 코드 예제와 같이 "익명 대리자"구문을 사용할 수 있습니다.

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

1

사용 위임, 그들은 입력 함수 포인터의 일종이다. 당신이 .NET 2.0을 사용하고 있기 때문에 http://msdn.microsoft.com/en-us/library/ms173171%28v=vs.80%29.aspx

+0

속성 가져 오기 도구에서 속성을 만들 수 있습니까? – jotbek

+0

예, 대리자는 변수의 한 유형이며 다른 변수가 전달되는 것과 동일한 방식으로 전달 될 수 있습니다. – Svarog