2016-09-16 22 views
1

好吧,所以這是(希望)一個非常簡單的修復,但我試圖創建一個允許外部訪問標籤的通用方法,現在Windows文檔確實給出了一個例子在這個單個案例用於從外部線程更改標籤文本的C#通用方法。

delegate void SetTextCallback(string text); 
...some other code ... 
private void SetText(string text) 
    { 
     // InvokeRequired required compares the thread ID of the 
     // calling thread to the thread ID of the creating thread. 
     // If these threads are different, it returns true. 
     if (this.textLable.InvokeRequired) 
     { 
      SetTextCallback d = new SetTextCallback(SetText); 
      this.Invoke(d, new object[] { text }); 
     } 
     else 
     { 
      this.textLable.Text = text; 
     } 
    } 

但是我想創建一些更通用的東西,我可以沿着指向該對象的指針的行傳遞某些東西,但是Windows窗體中的文本標籤不允許這樣做。理想的情況是這種情況,我想的東西做的東西沿着這些線路(這不會在工作形式顯然,只是explainational目的)

...code... 
private void SetText(string text, Label* lablePointer) 
{ 
    if (this.lablePointer.InvokeRequired) 
    { 
     SetTextCallback d = new SetTextCallback(SetText); 
     this.Invoke(d, new object[] { text }); 
    } 
    else 
    { 
     this.lablePointer.Text = text; 
    } 
} 

是否有這樣做的方法?我一直在尋找,但似乎沒有任何答案。

+0

你爲什麼要用指針? – NtFreX

+0

因爲我現在還不知道什麼更好(如果有更好的方法),但這只是爲了解決問題的要點。我希望我可以將它用於多個標籤,以便其他線程可以訪問它們,並節省我爲每個標籤寫入一百萬種這些方法。 – Metric

回答

3

你並不需要一個指針 - 你可以這樣做:

private void SetText(string text, Control control) 
{ 
    if (control.InvokeRequired) 
     control.Invoke(new Action(() => control.Text = text)); 
    else 
     control.Text = text; 
} 

可以使用Control代替Label因爲Text屬性從Control繼承(LabelControl派生)。這使它更通用一些。

不需要一個指針,因爲Label(和Control)爲參考類型,這意味着向Label對象的引用的副本壓入堆棧時SetText()被調用時,其必須通過同樣的效果一個C/C++中的指針。

(我猜你是C/C++程序員誰是切換到C#)。

+0

像魅力一樣工作,非常感謝。 (並且我是C/Java程序員) – Metric

0

如果你需要做多件事情在你的調用,您可以調用一個全功能做的一切一舉:

private void SetText(Label l, string text){ 
     if(l.InvokeRequired) 
     { 
      MethodInvoker mI =() => { 
       l.Text = text; 
       //representing any other stuff you want to do in a func 
       //this is just random left-over stuff from when I used it, 
       //it's there to show you can do more than one thing since you are invoking a function 
       lbl_Bytes_Total.Text = io.total_KB.ToString("N0"); 
       lbl_Uncompressed_Bytes.Text = io.mem_Used.ToString("N0"); 
       pgb_Load_Progress.Value = (int)pct; 
      }; 
      BeginInvoke(mI); 
     } 
     else 
     { 
      l.Text = text; 
     } 
    } 
+0

在需要一次完成多件事情的情況下調用函數的示例。 –