第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

調(diào)用調(diào)用中的匿名方法

調(diào)用調(diào)用中的匿名方法

楊__羊羊 2019-12-13 10:14:53
在想要在Control.Invoke中匿名調(diào)用委托的語法上有麻煩。我們嘗試了許多不同的方法,但都無濟(jì)于事。例如:myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); }); 其中someParameter在此方法本地以上將導(dǎo)致編譯器錯誤:無法將匿名方法轉(zhuǎn)換為類型“ System.Delegate”,因為它不是委托類型
查看完整描述

3 回答

?
慕田峪7331174

TA貢獻(xiàn)1828條經(jīng)驗 獲得超13個贊

因為Invoke/ BeginInvoke接受Delegate(而不是類型的委托),所以您需要告訴編譯器要創(chuàng)建什么類型的委托;MethodInvoker(2.0)或Action(3.5)是常見選擇(請注意,它們具有相同的簽名);像這樣:


control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});

如果需要傳遞參數(shù),則可以使用“捕獲的變量”:


string message = "Hi";

control.Invoke((MethodInvoker) delegate {this.Text = message;});

(注意:如果使用captures async,則需要謹(jǐn)慎一點,但是sync很好-即上述情況很好)


另一種選擇是編寫擴展方法:


public static void Invoke(this Control control, Action action)

{

    control.Invoke((Delegate)action);

}

然后:


this.Invoke(delegate { this.Text = "hi"; });

// or since we are using C# 3.0

this.Invoke(() => { this.Text = "hi"; });

當(dāng)然,您可以使用BeginInvoke:


public static void BeginInvoke(this Control control, Action action)

{

    control.BeginInvoke((Delegate)action);

}

如果不能使用C#3.0,則可以使用常規(guī)實例方法(大概是在Form基類中)執(zhí)行相同的操作。


查看完整回答
反對 回復(fù) 2019-12-13
?
千萬里不及你

TA貢獻(xiàn)1784條經(jīng)驗 獲得超9個贊

實際上,您不需要使用委托關(guān)鍵字。只需將lambda作為參數(shù)傳遞:


control.Invoke((MethodInvoker)(() => {this.Text = "Hi"; }));


查看完整回答
反對 回復(fù) 2019-12-13
?
翻閱古今

TA貢獻(xiàn)1780條經(jīng)驗 獲得超5個贊

我對其他建議有疑問,因為我有時想從我的方法中返回值。如果您嘗試將MethodInvoker與返回值一起使用,則似乎不喜歡它。所以我使用的解決方案是這樣的(非常高興聽到一種使它更簡潔的方法-我正在使用c#.net 2.0):


    // Create delegates for the different return types needed.

    private delegate void VoidDelegate();

    private delegate Boolean ReturnBooleanDelegate();

    private delegate Hashtable ReturnHashtableDelegate();


    // Now use the delegates and the delegate() keyword to create 

    // an anonymous method as required


    // Here a case where there's no value returned:

    public void SetTitle(string title)

    {

        myWindow.Invoke(new VoidDelegate(delegate()

        {

            myWindow.Text = title;

        }));

    }


    // Here's an example of a value being returned

    public Hashtable CurrentlyLoadedDocs()

    {

        return (Hashtable)myWindow.Invoke(new ReturnHashtableDelegate(delegate()

        {

            return myWindow.CurrentlyLoadedDocs;

        }));

    }


查看完整回答
反對 回復(fù) 2019-12-13
  • 3 回答
  • 0 關(guān)注
  • 610 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號