亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

調用調用中的匿名方法

調用調用中的匿名方法

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

3 回答

?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

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


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

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


string message = "Hi";

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

(注意:如果使用captures async,則需要謹慎一點,但是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"; });

當然,您可以使用BeginInvoke:


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

{

    control.BeginInvoke((Delegate)action);

}

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


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

TA貢獻1784條經驗 獲得超9個贊

實際上,您不需要使用委托關鍵字。只需將lambda作為參數傳遞:


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


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

TA貢獻1780條經驗 獲得超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;

        }));

    }


查看完整回答
反對 回復 2019-12-13
  • 3 回答
  • 0 關注
  • 611 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號