首先要了解一点,实例化子类时,会调用父类的构造函数,这也是子类中可以访问到父类中除私有变量外的其他变量的原因。
1.最简单应用
创建控制台应用,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
B b = new B();
}
}
public class A
{
public int param;
public A()
{
param = 0;
Console.WriteLine("The instance of A has been created!");
}
}
public class B:A
{
public B()
{
param = 1;
Console.WriteLine("The instance of B has been created!");
Console.ReadKey();
}
}
}
输出结果如下:
2.溢出情况
在父类A中存在其子类对象B,并且A的默认构造函数中会将子类B的子类赋值给共有变量_b(即使是私有变量亦会溢出)。下方代码无论是实例化A还是B都会导致溢出。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
A a = new A();//StackOverflowException
//B b = new B();//StackOverflowException
}
}
public class A
{
public int param;
public B _b;
public A()
{
param = 0;
Console.WriteLine("The instance of A has been created!");
//the reason of StackOverflowException
_b = new B();
}
}
public class B:A
{
public B()
{
param = 1;
Console.WriteLine("The instance of B has been created!");
Console.ReadKey();
}
}
}
运行结果如下:
3.问题原因
如篇头所述,在实例化子类的过程中会调用父类构造函数(父类存在多个构造函数使用:base()继承特定构造函数的方法在此不再赘述),故切记不可在父类中实例化子类对象,否则一定会造成堆栈溢出的错误。若需要在父类A中添加子类的实例B,可以对实例化后的父类对象中B类型的变量进行赋值,如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
A a = new A();
a._b = new B();
//B b = new B();//StackOverflowException
}
}
public class A
{
public int param;
public B _b;
public A()
{
param = 0;
Console.WriteLine("The instance of A has been created!");
//the reason of StackOverflowException
//_b = new B();
}
}
public class B : A
{
public B()
{
param = 1;
Console.WriteLine("The instance of B has been created!");
Console.ReadKey();
}
}
}
运行结果如下: