是否可以向集合中的类添加方法

本文关键字:添加 方法 可以向 集合 是否 | 更新日期: 2023-09-27 17:54:05

我试图在XNA中构建带有按钮和滑块的页面,并尝试了一些想法,但我似乎在保持"面向对象"的东西和让按钮和滑块保持有用之间陷入困境,而不添加太多实际的"按钮"answers"滑块"类。

所以我想知道是否有一种神奇的方式来实例化一个按钮类,然后添加一个方法,或者某种链接到一个方法,这样我就可以迭代我的按钮或滑块的集合,如果一个是'点击'执行与该按钮相关的特定方法?

最好是在父类中一个接一个地编写方法,代表我当时绘制的屏幕。

幻想代码示例:

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();

你可以在这里了解更多:

  • http://msdn.microsoft.com/en-us/library/bb311042.aspx

我对游戏编程的要求有模糊的理解,但我最近看到了一个关于这个框架的演示- http://dynobjects.codeplex.com/听起来它解决了一个类似的问题,如果不是相同的。