【问题标题】:How to use a dynamic button in another class如何在另一个类中使用动态按钮
【发布时间】:2015-09-06 08:39:48
【问题描述】:

我想制作一个动态按钮并控制它。

但我在行中有错误

MainMenuButton(true, Form);

如何改正?

Form1.cs

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        UI Teemp;

        ClientSize = new Size(Bounds.Width, Bounds.Height-35);
        Teemp.MainMenuButton(true, Form);
    }
}

和 UI.cs

class UI
{
    public void MainMenuButton(Boolean Mode, Form Form1)
    {
        if (Mode == true) //Create
        {
            System.Windows.Forms.Button StartB = new System.Windows.Forms.Button();
            Form1.Controls.Add(StartB);
            StartB.Text = "Start";
            StartB.Top = 300;
            //StartB.Bottom = 100;
            StartB.Left = 400;
        }
        else
        {
            //  this.Controls.Remove(StartB);
        }
    }
}

【问题讨论】:

  • 只需使用static 关键字,如@9​​87654325@,而不是Teemp.MainMenuButton(true, Form); 使用UI.MainMenuButton(true, Form);

标签: c# winforms button dynamic


【解决方案1】:

您必须首先创建 UI 类的实例。 UI Teemp; 只声明了一个 UI 类型的局部变量,但没有使用 UI 对象实例对其进行初始化。不能使用未初始化的局部变量。

在声明Teemp变量时,可以同时用UI对象实例初始化:

UI Teemp = new UI();


您的代码还有第二个问题。调用 MainMenuButton 时,您需要传递 Form 对象实例。在您的代码中,Form 是一个类型名称,并不指代对象实例。使用 this 关键字:

Teemp.MainMenuButton(true, this);

this 关键字是指正在使用它的类的当前实例。关于您的示例,this 将引用 Form1 对象实例。


我还想评论另一件事。从技术上讲这不是问题,但是将 MainMenuButton 的第二个参数命名为“Form1”可能会造成混淆,因为还有一个名为“Form1”的类型。对于 C#,一般建议变量名和参数名的首字母小写,而类型名的首字母大写。因此,您的 MainMenuButton 方法的源代码可能看起来像这样:

public void MainMenuButton(bool createButton, Form form)
{
    if (createButton)
    {
        System.Windows.Forms.Button startB = new System.Windows.Forms.Button();
        form.Controls.Add(startB);
        startB.Text = "Start";
        startB.Top = 300;
        //startB.Bottom = 100;
        startB.Left = 400;
    }
    else
    {
        //  this.Controls.Remove(startB);
    }
}

保持变量和参数名称与类型名称不同可以避免在读写代码时出现混淆,从而降低引入错误的风险:)

【讨论】:

  • 不完全正确。 UI 根本没有初始化,也没有为 null。
  • @FlatEric,好的,那么变量Teemp 的值是多少,如果你将它声明为UI Teemp;
  • 您在尝试访问它时会遇到编译错误。如果你用 null 初始化它,你会在运行时得到一个 NullReferenceException
  • 因此,它实际上是用 null 初始化的(因此是 NullReferenceException),您在这里与您的第一条评论相矛盾。阅读我回答中的第一句话:-)
  • @FlatEric,你是对的。我很困惑并在思考字段,但我们显然在这里处理局部变量......
猜你喜欢
  • 2019-08-11
  • 2020-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
相关资源
最近更新 更多