我对编程有点陌生,并且有一个关于什么是好的实践的问题。
我创建了一个代表球的类,它有一个函数 Jump()
,它使用 2 个计时器并使球上下移动。
我知道在 Winforms 中,每次想要重新绘制屏幕或其一部分时,都必须调用 Invalidate()
。我没有找到一个好的方法来做到这一点,所以我在我的类中引用了该表单,并在每次需要重新绘制球运动时在我的球类中调用 Invalidate()
。
(这可行,但我感觉这不是一个好的做法)
这是我创建的类:
public class Ball
{
public Form1 parent;//----> here is the reference to the form
public Rectangle ball;
Size size;
public Point p;
Timer timerBallGoUp = new Timer();
Timer timerBallGDown = new Timer();
public int ballY;
public Ball(Size _size, Point _p)
{
size = _size;
p = _p;
ball = new Rectangle(p, size);
}
public void Jump()
{
ballY = p.Y;
timerBallGDown.Elapsed += ballGoDown;
timerBallGDown.Interval = 50;
timerBallGoUp.Elapsed += ballGoUp;
timerBallGoUp.Interval = 50;
timerBallGoUp.Start();
}
private void ballGoUp(object obj,ElapsedEventArgs e)
{
p.Y++;
ball.Location = new Point(ball.Location.X, p.Y);
if (p.Y >= ballY + 50)
{
timerBallGoUp.Stop();
timerBallGDown.Start();
}
parent.Invalidate(); // here i call parent.Invalidate() 1
}
private void ballGoDown(object obj, ElapsedEventArgs e)
{
p.Y--;
ball.Location = new Point(ball.Location.X, p.Y);
if (p.Y <= ballY)
{
timerBallGDown.Stop();
timerBallGoUp.Start();
}
parent.Invalidate(); // here i call parent.Invalidate() 2
}
}
我想知道是否有更好的方法来做到这一点?
(对不起我的英语)
最佳答案
您应该在球中创建一个 Changed
事件,每当需要重新绘制球时就会触发该事件。
然后,您可以在表单和 Invalidate()
中处理此事件。
但是,最好将所有计时器替换为单个计时器,其形式在每个对象(球、砖 block 等)中调用公共(public) Tick()
方法。
然后,您可以在勾选每个对象后执行一次 Invalidate()
。
这也确保了所有对象都是同步的。
关于c# - Winforms:从不同的类调用输入表单函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9760210/