我正在尝试用图形学习 C#,目前使用 sdl.net。我想学习如何在屏幕上创建对象,但在这个疯狂的事情上坚持了三天。谷歌搜索了我能想到的一切,但我自己无法解决这个问题,我正在寻求帮助。
我将示例简化为最低限度。目前,我尝试通过在屏幕上单击鼠标并打印它们的编号来创建一些对象。在创建时,每个对象都有一个数字,我把它放在列表中,然后 foreach 每个对象。
但是当我打印对象列表时,每个对象都变得像最后一个对象,尽管构造函数显示它使用新编号创建了新对象。但是当我迭代列表时,每个对象都有相同的编号。
Constructor: object number:1
Show() object number:1
object count:1
Constructor: object number:2
Show() object number:2
Show() object number:2
object count:2
Constructor: object number:3
Show() object number:3
Show() object number:3
Show() object number:3
object count:3
什么时候应该:
Constructor: object number:3
Show() object number:1
Show() object number:2
Show() object number:3
object count:3
我做错了什么,我错过了什么?(我用 Windows 窗体和按钮尝试了相同的原理,效果很好)
我的简化代码:
using System;
using System.Collections.Generic;
using System.Drawing;
using SdlDotNet.Graphics;
using SdlDotNet.Input;
using SdlDotNet.Core;
using Font = SdlDotNet.Graphics.Font;
public class KeyboardTest
{
private static Surface m_VideoScreen;
private static Surface m_DrawingSurface;
private static List<ball> ball_list=new List<ball>();//### THE OBJECT LIST ###
private static int num = 1;
class ball //### MY CLASS ###
{
private static int numeris;
public ball(int _numeris) //### CONSTRUCTOR ###
{
numeris = _numeris;
System.Diagnostics.Debug.WriteLine("Constructor: object number:{0}", numeris);
}
public void show() //### VOID TO PRINT OBJECT NUMBER ###
{
System.Diagnostics.Debug.WriteLine("Show() object number:{0}", numeris);
}
}
public static void Main(string[] args) // ### MAIN VOID, SKIP THIS ###
{
m_VideoScreen = Video.SetVideoMode(800, 600, 32, false, false, false, true, true);
m_VideoScreen.Fill(Color.White);
m_DrawingSurface = Video.CreateRgbSurface(m_VideoScreen.Width, m_VideoScreen.Height, 32, 0, 0, 0, 0, true);
m_DrawingSurface.Fill(Color.White);
Events.Quit += new EventHandler<QuitEventArgs>(ApplicationQuitEventHandler);
Events.Tick += new EventHandler<TickEventArgs>(ApplicationTickEventHandler);
Events.TargetFps = 1;
Events.MouseButtonDown += new EventHandler<MouseButtonEventArgs>(ApplicationMouseButtonEventHandler);
Events.Run();
}
private static void ApplicationMouseButtonEventHandler(object sender, MouseButtonEventArgs args)
{
if (args.Button == MouseButton.PrimaryButton && args.ButtonPressed==true)
{
ball_list.Add(new ball(num)); //### ADDING TO THE LIST ON MOUSE CLICK ###
num += 1;
}
}
private static void ApplicationTickEventHandler(object sender, TickEventArgs args)
{
m_VideoScreen.Blit(m_DrawingSurface);
foreach (ball temp in ball_list) //### PRINTING NUMBERS OF ALL OBJECTS IN LIST ###
{
temp.show();
}
m_VideoScreen.Update();
System.Diagnostics.Debug.WriteLine("object count:{0}", ball_list.Count);
}
private static void ApplicationQuitEventHandler(object sender, QuitEventArgs args)
{
Events.QuitApplication();
}
}