【问题标题】:Delete TextBox with Button in separate Class在单独的类中删除带有按钮的文本框
【发布时间】:2021-09-16 05:07:30
【问题描述】:

我想通过使用单独的类“Delete”和方法 .resetText() 从 TextBox 'txtName' 中删除值。 我无法在这个单独的类中访问我的 TextBox。 我该如何解决这个问题?

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

    public void butDelete_Click(object sender, EventArgs e)
    {
        Delete delete = new Delete();
    }
}


class Delete
{
    public Delete()
    {
        txtName.ResetText();
    }
}

【问题讨论】:

  • 您可以将文本框对象作为参数传递

标签: c# visual-studio winforms class textbox


【解决方案1】:

将文本框对象作为参数传递。

class Delete
{
    public Delete(TextBox txtName)
    {
        txtName.ResetText();
    }
}

【讨论】:

  • ref TextBox txtName 怎么样?
  • @Auditive 是必需的吗?我不这么认为。
  • @Auditive ref 这里使用意味着您可以创建一个 TextBox within Delete 的新实例,并将传入的 TextBox 完全替换为新实例。
【解决方案2】:

使用 Delete 方法的参数发送您的文本框控制:


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

    public void butDelete_Click(object sender, EventArgs e)
    {
        Delete delete = new Delete();
        delete.Delete(txtName);
    }
}


class Delete
{
    public Delete(Control control)
    {
         var txtBox = control as TextBox;
         if (txtBox == null)
            return;
         txtBox.ResetText();
    }
}

【讨论】:

  • 你不需要这个:var txtBox = control as TextBox;ResetText() 属于Control 类。如果您使用属于 TextBoxBase 类的Clear() 方法,情况会有所不同。但是,在这种情况下,您将添加一个不同的约束,public Delete(TextBoxBase control)。空检查也不是必须的,写control?.ResetText();
  • Control 和 TextBoxBase 是引用类型,我认为这并不重要。 TextBoxBase 类也继承自 Control )
  • 这与引用类型无关,而是与继承有关。如果您需要使用属于 Control 类的方法,则将参数定义为 Control control 然后强制转换为 TextBox 是没有意义的。只需将参数定义为TextBox 或不强制转换。如果要向 TextBox 类添加约束,请将其添加到参数中。否则,不清楚为什么将 Button 作为参数传递什么都不做。
  • 我认为这是正确的!我的方法更具扩展性,例如,如果进一步,想要为 RichTextBox 或 ComboBox 等进行重置。
  • 如果你想让它更通用,如前所述和描述的,方法就是:public Delete(Control control) { control?.ResetText(); }。现在你可以通过任何控件了。
【解决方案3】:

已解决

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

    public void butDelete_Click(object sender, EventArgs e)
    {
        Delete delete = new Delete(txtName);
    }
}


class Delete
{
    public Delete(TextBox txtName)
    {
        txtName.ResetText();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 2013-03-15
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多