我想在对象初始化时覆盖一个方法,如下所示:
Button = new Button(parameter1, parameter2){
public override onClicked(){
//implementation
}
};
这就是得到的:
public class Button:Entity
{
protected Texture2D texture2D;
public Vector2 vector2;
public Button(Texture2D image, Vector2 position
{
this.image = image;
this.position = position;
this.action = action;
}
public abstract void onClicked();
}
abstract class Entity
{
public Vector2 position;
public int radius = 20;
protected Texture2D image;
public virtual void draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(image,position,Color.White);
}
}
我只是尝试创建一个类似我之前说过的实现,但它不会编译。如何编译或实现这样的“每个实例”覆盖?
答案 0 :(得分:3)
public class Button:Entity
{
//Vector, Radius and texture are already part of Button, since it extend Entity
public EventHandler onClicked;
public Button(Texture2D image, Vector2 position)
{
this.image = image;
this.position = position;
this.action = action;
}
}
abstract class Entity
{
public Vector2 position;
public int radius = 20;
protected Texture2D image;
public virtual void draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(image,position,Color.White);
}
}
并以这种方式使用它:
Button = new Button(parameter1, parameter2){
onClicked = new EventHandler(NameOfYourMethod);
};