2011-06-21 41 views
1

這是關於從另一個線程更新UI的系列文章中的第二個問題。我正在嘗試使用委託告訴UI執行更新函數(不需要傳遞數據)。我在UI線程創建的代表,並宣佈它的UI線程的頂部:如何在.net C++中編寫委託代碼

delegate void MyDel(); 
public ref class Form1 : public System::Windows::Forms::Form 
{ 
    // ..... 
    void testFunc() 
    { 
     this->local_long_textBox->Text = "Test!!!!!!!"; 
    } 
private: 
    void startUp() 
    { 
     MyDel^ DelInst = gcnew MyDel(this,&CotStinger::Form1::testFunc); 

我想在創建時DelInst傳遞到另一個線程,但是當我試圖聲明MyDel像這樣在上面一個extern另一個模塊:

extern delegate MyDel; 

我得到的錯誤:

Error C2146: syntax error : missing ';' before identifier 'MyDel' .

如果我試試這個

extern delegate void MyDel(); 

我得到的錯誤:

Error C2144: syntax error : 'void' should be preceded by ';'

那麼,如何得到其他類識別委託類型,所以我可以通過委託指針構造?

回答

2

delegate關鍵字用於定義代理類型,而不是聲明碰巧是某種委託類型的變量。也就是說,一旦委託類型被定義,你不需要任何關鍵字delegate

此外,託管類型的全局變量不允許在C++/CLI中使用;通常的解決方法是使用公共靜態數據成員的邏輯靜態管理類作爲全局起作用的:

delegate void MyDel(); 
private ref struct Globals abstract sealed 
{ 
    static MyDel^ MyDelInstance; 
}; 

// ... 

Globals::MyDelInstance = gcnew MyDel(this, &CotStinger::Form1::testFunc); 

So how do I get the other class to recognize the delegate type so I can pass the delegate pointer to the constructor?

同樣作爲任何其他類型的 - 把它放在一個頭文件,這兩個類都可以#include

+0

我複製了上面的代碼,並得到以下消息:錯誤C3145:'myDelInstance':全局變量或靜態變量可能沒有託管類型'CotStinger :: MyDel ^' – user758362

+0

@ user758362:對不起,我的部分疏忽了。回答編輯。 – ildjarn

+0

該消息的其餘部分是:可能不聲明全局變量或靜態變量,或引用gc堆中的對象的本機類型的成員 – user758362