开发者

There is an error in my C# program that occur a stack overflow Exception [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

i have 2 forms. one of them is a form that User select a school class so 开发者_运维知识库click OK. I use

public int[] grad_class=new int[2];

for save which School class has selected. (list of classes is COMBO BOX) after that i open another new form to edit information of that class' students. i use Switch like this:

switch(grad_class)
{
   case "11": something to do..., break;
   case "12": something to do..., break;
}

But My problem : I define "grad_class" in form No.1 . so when i want to use that i have to do this:

form1 f1 = new form1();
f1.grade_class;

and in form No.2 i call this code. in form No.1 i call:

form2 f2 = new form2();    

OCCUR STACK OVERFLOW EXCEPTION !!!


You state:

form1 f1 = new form1();
f1.grade_class;

and in form No.2 i call this code. in form No.1 i call:

form2 f2 = new form2();    

Well, there's your issue right there. You state that in form1 you call form2.ctor and in form2 you call form1.ctor. So your code looks like this:

public form1() {
    var f2 = new form2();
}

public form2() {
    var f1 = new form1();
}

Well, of course this results in a stack overflow. These are mutally recursive functions. You have no return condition, so you exhaust your stack space. Quite simply, what is happening is that the machine has to store state about where to go next when a method is finished. It typically stores this information in space called the stack. The stack is bounded though, so if you push too many "this is where to go next" blocks onto the stack by repeatedly invoking methods, you will exhaust this stack space and hit the infamous stack overflow exception.

Edit: You said:

namespace TeacherBook {
    public partial class ChooseGrade : Form {
        public int[] grad_class=new int[2]; //int array for grade & class (first for Grade,second for class) 
        EditStudent StdForm = new EditStudent();
    }
namespace TeacherBook {
    public partial class EditStudent : Form {
        ChooseGrade ChGrade = new ChooseGrade(); // define form 
    }
}

Effectively what I suspected. You have a field initializer in ChooseGrade that instantiates a new instance of EditStudent. But EditStudent has a field initializer that instantiates a new instance of ChooseGrade. So when you instantiate a new instance of ChooseGrade, this causes the constructor for EditStudent to be invoked, which causes the constructor for ChooseGrade to be invoked, which causes the constructor for EditStudent to be invoked, and on and on it goes until you overflow your stack.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜