从表单调用方法 [英] Invoke a method from a form

查看:25
本文介绍了从表单调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从表单中调用带有参数的方法?我知道我可以使用一个动作.我想闭包在动作中捕获变量以允许它工作.不过,我觉得方法会更干净.我的代码库中有很多这样的操作,我不喜欢它们隐藏在难以重构的方法中.

Is it possible to invoke a method with parameters from a form? I know I can use an action. I suppose closure captures variables in actions to allow this to work. Still, I feel like Methods would be cleaner. I have a lot of these actions in our codebase and I don't like them sitting about hidden inside of methods where they are hard to refactor.

    public static void Main()
    {
        Form form = new Form();
        Action action = () => form.SendToBack();//(Now Imagine this Action is 50 lines of code and there's 15 of them...Then it should make sense as to why I want to seperate this logic out into classes and methods.
        //Action action2 = AMethod(form);//doesnt work

        Task.Factory.StartNew(
            () =>
            {                    
                //form.Invoke(AMethod);//doesnt work see error below...also no params
                form.Show();                    
                form.Invoke(action);
                Application.Run();
            }
         );
        Console.Read();
    }

    public static void AMethod(Form form)
    {
        form.SendToBack();
    }

更新
我根据评论尝试了重载 form.Invoke(AMethod,form); 并且我得到错误:

参数 1:无法从方法组"转换为System.Delegate"

Argument 1: cannot convert from 'method group' to 'System.Delegate'

推荐答案

Control.Invoke() 的重载是:

The overloads for Control.Invoke() are:

  public Object Invoke(Delegate method)
  public Object Invoke(Delegate method, params Object[] parameters)

第一个参数类型是麻烦制造者,Delegate 是一个无类型"的委托类型.C# 编译器坚持您使用类型化委托,以便它可以验证您正在调用具有正确签名的方法.在您的情况下,这意味着您必须传递 Action

类型的委托对象.要求它仅从方法group"推断委托类型是它不会做的.有点烦人,但类型安全在 C# 中是最重要的.

The first argument type is the troublemaker, Delegate is an "untyped" delegate type. The C# compiler insists that you use a typed delegate so that it can verify that you are invoking a method with the proper signature. Which in your case means that you have to pass a delegate object of type Action<Form>. Asking it to infer the delegate type from just the method "group" is what it won't do. Somewhat annoying, but type safety is paramount in C#.

所以正确的语法是:

  form.Invoke(new Action<Form>(AMethod), form);

没有赢得任何奖品.很难忽略捕获表单变量的 lambda 语法:

Which doesn't win any prizes. Hard to pass up the lambda syntax that captures the form variable:

   form.Invoke(new Action(() => AMethod(form)));

匿名方法也可以,但出于同样的原因,您必须进行强制转换:

An anonymous method works too, but you have to cast for the same reason:

   form.Invoke((Action)delegate { AMethod(form); });

这篇关于从表单调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆