You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在方法内部修改调用该方法的TextBox对象?

解决方法

核心是利用事件参数里的sender对象,它就是触发当前事件的TextBox实例,修改步骤如下:

  1. 给periodFix方法添加TextBox类型的参数,用来接收需要处理的文本框:
public void periodFix(TextBox textBox)
{
    textBox.Text = textBox.Text.Trim();
    if (textBox.Text.Length > 0)
    {
        // 无需转char数组,直接访问首字符更简洁
        if (textBox.Text[0] != '.')
        {
            textBox.Text = "." + textBox.Text;
        }
    }
    else
    {
        textBox.Text = ".";
    }
}
  1. 在事件处理方法中,将sender强制转换为TextBox类型后传入periodFix:
private void textBox7_Leave_1(object sender, EventArgs e)
{
    // 先判断类型避免转换错误
    if (sender is TextBox targetTextBox)
    {
        periodFix(targetTextBox);
    }
}

这样不管哪个TextBox的Leave事件调用该方法,都会自动处理对应的文本框。你还可以将这个事件处理方法绑定给所有需要的TextBox的Leave事件,彻底实现代码复用。


内容的提问来源于stack exchange,提问作者BlakeWritesCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 07:26:11