【问题标题】:Adding buttons by a function通过函数添加按钮
【发布时间】:2014-12-17 18:54:56
【问题描述】:

我想添加一个按钮,使用一个函数将所有参数放在一行中,以保持它的整洁。但是如果我尝试通过This.Controls.Add 添加按钮,我会收到错误,因为该函数是静态的。我应该写什么而不是This(类似于Form1.Controls.Add),这样我就可以在一个函数中完成所有事情?

【问题讨论】:

  • 如果你需要访问表单,为什么方法首先是静态的?

标签: c# winforms button static


【解决方案1】:

您可以将表单作为静态函数的参数:

public static void CreateButton(Form targetForm, param1, param2, ...) {
    Button b = new Button();
    ...
    targetForm.Controls.Add(b);
}

...但是除非这种方法将用于将按钮添加到各种表单中,否则我看不到将其设为静态的好处。这似乎是一种 OO 反模式。我可能会将其设为非静态并使用this

【讨论】:

    【解决方案2】:

    我只想让你的函数返回按钮:

    //Usage
    this.Controls.Add(CreateButton(...));
    
    //Function def 
    public static Button CreateButton(...)
    {
       Button createdButton = new Button();
       ...
       return createdButton;
    }
    

    Assignment 返回分配的结果(因此您可以将它们链接起来)。所以要内联分配:

    //With a variable (I did *not* say it was good practice to do this)
    this.Controls.Add(myVar = CreateButton(...));
    

    【讨论】:

    • 但是我怎么才能找到新按钮呢?我需要指向它的变量。我知道我可以得到它,然后添加它。但我只想用一行来完成
    猜你喜欢
    • 1970-01-01
    • 2017-12-02
    • 2021-07-02
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    相关资源
    最近更新 更多