我正在尝试使用按钮和滑块在XNA中构建页面,并尝试了一些想法,但我似乎陷入了保持“面向对象”并使按钮和滑块保持有用而不增加太多内容之间的问题。实际的'Button'和'Slider'类。
所以我想知道是否有一种神奇的方式来实例化一个Button类,然后添加一个方法,或某种方法的链接,以便我可以迭代我的按钮或滑块集合,如果一个是'hit'执行与该按钮相关的特定方法?
我最好在父类中一个接一个地编写方法,代表当时的画面。
幻想代码示例:
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; }
}
答案 0 :(得分:6)
我认为你正在寻找代表参加活动。我建议在这里使用事件:
首先,创建一个包含课堂内所有内容的公共事件,例如:
public delegate void ClickedHandler(object sender, EventArgs e);
public event ClickedHandler Clicked;
private void OnClidked()
{
if (Clicked != null)
{
Clicked(this, EventArgs.Empty);
}
}
然后,在按钮类中创建一个方法,检查是否单击了
public void CheckClick(Vector2 click)
{
if (/* [i am clicked] */)
{
OnClicked();
}
}
在按钮外,您可以订阅点击的事件,如下所示:
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 **/
}
要查找有关活动的更多信息,请转到此处:http://www.csharp-station.com/Tutorials/lesson14.aspx。希望这会有所帮助。
答案 1 :(得分:0)
C#有扩展方法,可能符合您的需求。
扩展方法在某些静态类中使用特殊语法定义。一个样本可能是:
public static char GetLastChar(this string some)
{
return some[some.length - 1];
}
string a = "hello world";
char someChar = a.GetLastChar();
您可以在此处了解更多信息:
答案 2 :(得分:0)
我对游戏编程的要求含糊不清,但最近我看到了关于这个框架的演示文稿 - http://dynobjects.codeplex.com/ 听起来像是解决了类似的问题。