c# - 从派生表单访问基本表单的控件时有什么更好的主意

标签 c# winforms

我不知道应该如何访问 ase 表单的控件。

  1. 将控件的访问修饰符设置为“ protected ”。

    public class BaseForm
    {
        protected System.Windows.Forms.Button button1;
        protected System.Windows.Forms.Label label1;
    }
    
    public class Form2 : BaseForm
    {
        public Form2()
        {
            button1.Text = "J. Doe";
            label1.Text = "Kim";
        }
    }
    
  2. 保持私有(private)控制权并创建属性(property)

    public class BaseForm
    {
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label label1;
    
        public Button Button1
        {
            get { return button1; }
        }
        public Label Lable1
        {
            get { return label1; }
        }
    
    }
    
    public class Form2 : BaseForm
    {
        public Form2()
        {
            Button1.Text = "J. Doe";
            Lable1.Text = "Kim";
        }
    }
    

哪个更好?

最佳答案

Protected 告诉 VS 这些元素只能被声明它们的类的子类访问

public class BaseForm
{

    //All BaseForm child classes will have access to the protected elements
    protected System.Windows.Forms.Button button1;
    protected System.Windows.Forms.Label label1;
}

public class Form2 : BaseForm
{
    public Form2()
    {
        button1.Text = "J. Doe";
        label1.Text = "Kim";
    }
}

在你的代码中,BaseForm是一个父类,所以继承父类的方法是最好的选择。

public class BaseForm
{
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Label label1;

    public Button Button1
    {
        get { return button1; }
    }
    public Label Lable1
    {
        get { return label1; }
    }

}

public class Form2 : BaseForm
{
    public Form2()
    {
        Button1.Text = "J. Doe";
        Lable1.Text = "Kim";
    }
}

这里用到访问器,一般用来给全局变量传递参数,重赋局部变量的值,用来在两个独立的类之间传递参数

如果你总是要将一个类扩展到 BaseForm,请使用 proted,如果你想从任何地方调用变量,请使用访问描述符 (get; set;)

关于c# - 从派生表单访问基本表单的控件时有什么更好的主意,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49185399/

相关文章:

c# - 在 C# Windows 应用程序中停止线程应用程序?

c# - 模式匹配失败

c# - 使用不同的参数重新加载表单 c#

c# - 当 openFileDialog 从第二个表单返回结果时,Modalform 关闭

C# 无法在设计器 Visual Studio 2010 中存储设计时间值

c# - .NET 4 中的 URL 重写?

c# - .tfignore 不是忽略文件

c# - 在特定时间执行功能

C# UserControl.VerticalScroll.Value 未设置

c# - Datagridview单元格样式更新