开发者

Why when I try to instantiate a class instance, do I get StackOverFlowException?

I keep getting StackOverFlowException whenever I instantiate an instance of A class. I know it 开发者_如何学编程has got something to do with the fact that A.b field is of type derived from class A. But why would that cause an exception?

static void Main(string[] args)
{
     A a = new A(); // exception
}

class A 
{
    private B b = new B();
}

class B:A {}

thank you


Because B is inherited from A, each time you're creating an A, a B is created, which, in turn creates another B. You've essentially created an endless loop of class creation.


Here is what is happening under the hood

  1. Create a new instance of A
  2. As a consequence it creates an instance of B for the private field b
  3. B derives from A and hence has it's own field b. At this point it goes back to step #2 and repeats until a stack overflow occurs


Because A has a reference to a class B, which derives from A. Due to constructor chaining, the ctor of B calls the ctor of A, leading to a creation of a new instance of B, which will continue until eternity or a StackOverflowException.


Its because constructors are called recursively


Because you ave a circular reference

in order to make a B you have to make an A In order to Make an A you have to Make an B

As such it tunnels downwards.

To fix it, dont initialise the private field.


If you want your subclass to know about any derivative types, use generics. This is featured heavily in the CSLA.NET Framework.

public class A<T> where T : A<T>
{

}

public class B : A<B>
{

}

Note that A doesn't reference B, but you get to encapsulate the derived type at base level on methods etc.


When you create an instance of A, it will create an internal instance of B.... which will - guess what - create an internal instance of B which will - guess what - create an internal instance of B which will - guess what - create an internal instance of B.

This is because the B constructor goes on the A constructor which is recursive. Stack overflow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜