Sal*_*ara 2 c# stack-overflow visual-studio-2010 winforms
我在Visual Studio 2010中创建了以下类:
public class Bat : Form1
{
public int BatLocation;
public void draw()
{
Pen batPen = new Pen(Color.Black);
batPen.Width = 10;
playArea.DrawRectangle(batPen, BatLocation, (picPlayArea.Height - 30), 50, 10);
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试创建一个类的实例时,我得到一个堆栈溢出异常,建议我确保我没有无限循环或无限递归.我尝试过两种不同的方式创建实例,如下所示:
Bat bottomBat;
bottomBat = new Bat();
Run Code Online (Sandbox Code Playgroud)
和
Bat bottomBat = new Bat();
Run Code Online (Sandbox Code Playgroud)
但是当我尝试运行程序时,两种方式都会返回相同的错误.我也尝试过使用和不使用public修饰符的类定义.
我对编程很陌生,不知道可能导致这个问题的原因.难道我做错了什么?
编辑:Bat类的代码是我目前所拥有的一切,没有为它创建一个特定的构造函数...没想到我需要?
无论如何,这里是完整的Form1类:
public partial class Form1 : Form
{
// Define various objects for the game
public Graphics playArea;
Bat bottomBat = new Bat();
public Form1()
{
InitializeComponent();
// Create instances of objects
playArea = picPlayArea.CreateGraphics();
//bottomBat = new Bat();
// Delegate the mouseMove event for picPlayArea
picPlayArea.MouseMove += new MouseEventHandler(picPlayArea_MouseMove);
}
private void picPlayArea_MouseMove(object sender, MouseEventArgs e)
{
bottomBat.Location = e.X;
}
private void btnExit_Click(object sender, EventArgs e)
{
string msg = "Are you sure you want to exit?",
title = "Confirm Exit";
DialogResult res = MessageBox.Show(msg, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
Environment.Exit(0);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
// This is where most of the functionality is executed within the game
playArea.Clear(Color.White);
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
}
Run Code Online (Sandbox Code Playgroud)
看来你已经以不可能的方式结合了继承和组合.基Form1类型具有声明为派生Bat类型的字段.此外,它使用字段初始化程序将其初始化为该类型的新实例.显然,你有一个乌龟一直在向下的问题:当你创建一个Bat(或者Form1那个问题)时,字段初始化程序将运行 - 这将创建另一个的实例Bat,这反过来将创建另一个 Bat,等等,理论上无穷无尽.(在实践中:直到你用完堆栈空间).
这是一个简单的解决方案,可以解决堆栈溢出问题,但可能不是"大图片"中最合适的设计:
public class Bat
{
public void Draw(Graphics playArea)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
注意这个类型不再是子类Form1; 它直接从System.Object.现在,当创建它们的实例时Form1,Bat类和类都不会表现出无限递归.
如果不知道这里的终极目标,很难建议最好的解决方案.我建议你考虑一下设计这些课程的最佳方法.我认为您需要花一些时间来学习C#编程语言,OO设计以及WinForms细节.我想你实际上是想在OnPaint这里覆盖虚拟方法.
| 归档时间: |
|
| 查看次数: |
945 次 |
| 最近记录: |