为了账号安全,请及时绑定邮箱和手机立即绑定

调用调用中的匿名方法

调用调用中的匿名方法

杨__羊羊 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 关注
  • 519 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信