我正在尝试使用按钮和滑块在XNA中构建页面,并尝试了一些想法,但我似乎陷入了保持"面向对象"并使按钮和滑块保持有用而不会增加实际"按钮"之间的问题'和'滑块'课程.
所以我想知道是否有一种神奇的方式来实例化一个Button类,然后添加一个方法,或者某种方法的链接,以便我可以迭代我的按钮或滑块集合,如果有一个'命中'执行与该按钮相关的具体方法?
我最好在父类中一个接一个地编写方法,表示当时的屏幕绘图.
幻想代码示例:
class Room // Example class to manipulate
{
public bool LightSwitch;
public void Leave() { /* Leave the room */ }
}
class Button
{ // Button workings in here
public bool GotPressed(/*click location */)
{ /* If click location inside Rect */ return true; }
public void magic() {} // the method that gets overidden
}
public class GameScreen
{
public Room myRoom;
private List<Button> myButtons;
public GameScreen()
{
myRoom = new Room();
myRoom.LightSwitch = false;
List<Button> myButtons = new List<Button>();
Button B = new Button();
// set the buttons rectangle, text etc
B.magic() == EscapeButton(B);
myButtons.Add(B);
Button B = new Button();
B.magic() == SwitchButton(B);
myButtons.Add(B);
}
public void Update() // Loop thru buttons to update the values they manipulate
{ foreach (Button B in myButtons)
{ if(B.GotPressed(/*click*/)) { B.magic(B) } }}
// Do the specific method for this button
static void EscapeButton(Button b)
{ myRoom.Leave(); }
static void SwitchButton(Button b)
{ myRoom.LightSwitch = true; }
}
Run Code Online (Sandbox Code Playgroud)
我认为你正在寻找代表参加活动.我建议在这里使用事件:
首先,创建一个包含课堂内所有内容的公共事件,例如:
public delegate void ClickedHandler(object sender, EventArgs e);
public event ClickedHandler Clicked;
private void OnClidked()
{
if (Clicked != null)
{
Clicked(this, EventArgs.Empty);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在按钮类中创建一个方法,检查它是否被单击
public void CheckClick(Vector2 click)
{
if (/* [i am clicked] */)
{
OnClicked();
}
}
Run Code Online (Sandbox Code Playgroud)
在按钮外,您可以订阅点击的事件,如下所示:
var b = new Button();
b.Clicked += new ClickedHandler(b_Clicked);
/* [...] */
private void b_Clicked(object sender, EventArgs e)
{
/** do whatever you want when the button was clicked **/
}
Run Code Online (Sandbox Code Playgroud)
要了解有关活动的更多信息,请访问:http://www.csharp-station.com/Tutorials/lesson14.aspx.希望这可以帮助.