我有一段代码
public class A
{
public A()
{
Console.WriteLine("A");
}
B b = new B("From A");
}
public class B : A
{
public B()
{
Console.WriteLine("B");
}
public B(string str) //Getting exception here
{
Console.WriteLine("In B " + str);
}
}
public class C : A
{
B b = new B("From C");
public C()
{
Console.WriteLine("C");
}
}
class Program
{
static void Main(string[] args)
{
new C();
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我知道在调用基础构造函数之前首先初始化所有属性,但是我无法找到为什么我得到Stackoverflow异常.任何帮助?谢谢
Mar*_*den 10
因为B继承自A,所以它继承了
B b = new B("From A");
Run Code Online (Sandbox Code Playgroud)
领域.因此,无论何时创建B对象,它都会在无限递归链中创建另一个B对象.
因此,在您拥有的实际程序中,您将创建一个C对象.然后使用带有字符串的重载("From C")构造一个B对象.然后,您在该构造函数上获得异常,因为它然后以递归方式创建无限B对象.