[英]Access child class instance in parent class constructor
我搜索了很多东西,但是没有找到解决我问题的方法。
我创建了一个基类MyProjectBase
,该基类继承自System.Windows.Forms.Form
类。 这个基类应该调用静态类General
一些静态函数。 例如,我有一个函数CheckSecurity(Form frm)
。 我需要MyProjectBase
每个子类都应调用此CheckSecurity()
函数,但要具有其自己的子类实例。 这是示例代码:
public static class General {
public static void CheckSecurity(System.Windows.Forms.Form frm) {
// Does Security Check on frm
}
}
public class MyProjectBase : System.Windows.Forms.Form {
public MyProjectBase() {
General.CheckSecurity(this);
}
}
public class ChildA : MyProjectBase {
// I need this class instance to call the General.CheckSecurity() function
// but pass its own ChildA instance to that function automatically, without
// even writing constructor of ChildA class
}
可能吗? 我可以使用GetType()
获取ChildA
类中ChildA
类的类型名称,但不能获取ChildA
类的实际实例。
编辑:如果有解决此问题的任何替代方法,请告诉我有关。
编辑解决方案:实际上,我想访问ChildA
类的控件,该类实际上是一个Form
对象。 我刚刚修改了MyProjectBase类,如下所示:
public class MyProjectBase : System.Windows.Forms.Form {
public MyProjectBase() {
InitializeComponent();
}
private void MyProjectBase_Load(object sender, EventArgs e){
General.CheckSecurity(this);
}
}
而且有效。 之前它不起作用,因为没有初始化ChildA
对象。
永远不会少。 感谢大家的帮助。 我解决了问题。
您当前的实现应完全按照您的要求工作。
internal class Program
{
private static void Main()
{
BaseClass bc = new BaseClass(); // outputs xxx.BaseClass
BaseClass dc = new DerivedClass(); // outputs xxx.DerivedClass
}
}
public class BaseClass
{
public BaseClass()
{
Console.WriteLine($"{GetType()}");
}
}
public class DerivedClass: BaseClass
{
// default constructor calls base constructor
// and `this` object refers to DerivedClass instance
}
或您的特定代码:
public static class General {
public static void CheckSecurity(System.Windows.Forms.Form frm) {
// Does Security Check on frm
frm.GetType(); // check the type here
}
}
public class MyProjectBase : System.Windows.Forms.Form {
public MyProjectBase() {
General.CheckSecurity(this);
}
}
public class ChildA : MyProjectBase {
/*
You don't have to add your own constructor. By default
MyProjectBase class constructor is called every time you create
new instance of ChildA.
And in MyProjectBase constructor you have `this` of the origin object,
so it has the right type `ChildA` for objects of type ChildA.
*/
// I need this class instance to call the General.CheckSecurity() function
// but pass its own ChildA instance to that function automatically, without
// even writing constructor of ChildA class
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.