是否可以将方法添加到集合中的类中?
我想在XNA中用按钮和滑块创建页面,并尝试了一些想法,但我似乎在保持“面向对象”的东西和让按钮和滑块保持有用而没有多加实际'按钮'和'滑块'类。是否可以将方法添加到集合中的类中?
所以我想知道是否有一种神奇的方式来实例化一个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; }
}
我认为你正在寻找为事件的代表。我推荐你使用事件:
首先,在你的类创建的一切公众活动,如:
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。希望这可以帮助。
C#有扩展方法,这可能满足您的需求。
扩展方法在某些静态类中用特殊的语法定义。这方面的一个样本可能是:
public static char GetLastChar(this string some)
{
return some[some.length - 1];
}
string a = "hello world";
char someChar = a.GetLastChar();
您可以在这里了解更多:
从我可以收集到的东西扩展(或添加)静态方法,我想要做的是重写一个perticual方法,以便当我遍历集合并激发相同的方法时,它做了不同的事情。 – Trinnexx 2011-05-02 15:39:24
阅读答案很重要。读取Msdn链接,你会发现一个扩展方法的行为像一个实例。 – 2011-05-03 06:50:02
+1击败我吧 – 2011-05-02 14:35:36
这就是我想要的,我只是还没有看到事件的一个好例子,msdn的例子似乎增加了很多faff并且隐藏了更多的实际用途! 非常感谢! – Trinnexx 2011-05-03 07:45:40