0

除了初始化的普通类之外,我什么都看不到。

这是类,Bet.cs 类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lab_ADayAtTheRaces
{
public class Bet : Form1
{
    public int Bets_Joe;
    public int Bets_Bob;
    public int Bets_Al;
    public int Dog_Joe;
    public int Dog_Bob;
    public int Dog_Al;

    public int Amount;
    public int Dog;
    public Guy Bettor;

    public string GetDescription()
    {
        Amount = (int)numericUpDownBucksToBet.Value;
        Dog = (int)numericUpDownDogToBetOn.Value;
        //Bettor =
        return Bettor + " placed a bet in the amount of " + Amount + " bucks on dog number " + Dog;
    }

    public int PayOut(int Winner)
    {
        return Winner;
    }

    public void MakeBets()
    {
        if (joeRadioButton.Checked == true)
        {
            Bets_Joe = (int)numericUpDownBucksToBet.Value;
            Dog_Joe = (int)numericUpDownDogToBetOn.Value;
        }

        else if (bobRadioButton.Checked == true)
        {
            Bets_Bob = (int)numericUpDownBucksToBet.Value;
            Dog_Bob = (int)numericUpDownDogToBetOn.Value;
        }

        else if (alRadioButton.Checked == true)
        {
            Bets_Al = (int)numericUpDownBucksToBet.Value;
            Dog_Al = (int)numericUpDownDogToBetOn.Value;
        }
    }

}

}

以下是引发异常的代码:

namespace Lab_ADayAtTheRaces
{
public partial class Form1 : Form
{
    Bet bets = new Bet(); //**THIS LINE THROWS THE STACKOVERFLOW EXCEPTION**

    Greyhound[] dogs = new Greyhound[3];

它想让我多说点什么,但我没有什么要补充的了,所以我只是在这里和这里添加一些行。它想让我多说点什么,但我没有什么要补充的了,所以我只是在这里和这里添加一些行。它想让我多说点什么,但我没有什么要补充的了,所以我只是在这里和这里添加一些行。它想让我多说点什么,但我没有什么要补充的了,所以我只是在这里和这里添加一些行。非常感谢任何帮助......提前感谢克里斯蒂安

4

1 回答 1

11

您的Bet继承自Form1,因此Bet()将调用 to Form1()Form1()并将再次调用 toBet()内部 -> 一次又一次 ->StackOverflow

提示:我们不应该像这样在类的构造函数或类定义中调用类的构造函数:

public class Form1 : Form {
    public Form1(){
    }
    public Form1(string s){
    }
    public Form1 f = new Form1();//this will throw StackOverflowException
    public Form1 f = new Form1("");//this will also throw StackOverflowException       
    //Form2 inherits from Form1
    public Form2 f = new Form2(); //this will throw StackOverflowException
}
//or
public class Form1 : Form {
    public Form1(){
        Form1 f = new Form1();//This will throw stackoverflowexception
        Form1 f = new Form1("");//This won't throw any exception
    }
    public Form1(string s){
    }
}

当一个类被初始化时,在调用构造函数之前首先初始化所有成员,因此Bet bets = new Bet();在初始化你的Form1. 所以你必须避免它。要初始化new Bet(),您应该在某个事件中调用它,以便永远不会通过调用构造函数来触发该事件,例如Load.

Bet bets;//Just declare it without initializing it
private void Form1_Load(object sender, EventArgs e){
   bets = new Bet();
}
于 2013-09-02T11:11:02.453 回答