我不知道应该如何访问 ase 表单的控件。
将控件的访问修饰符设置为“ 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"; } }
保持私有(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/