Component.cs
public abstract class Component
//abstract to it has to be inherited and any child will be
//強制使用Draw & Update類。
{
public abstract void Draw(GameTime gameTime, SpriteBatch spriteBatch)。
public abstract void Update(GameTime游戲時間)。
Button.cs
public abstract class Button : Component//抽象到它必須被繼承,任何孩子都會被。
//強制使用Draw & Update類。
{
// #region Fields
private MouseState _currentMouse;
private SpriteFont _font;
private MouseState _previousMouse;
private Texture2D _texture;
// #endregion
public event EventHandler Click;
public Color TextColour { get; set; }
public Vector2 Position { get; set; }
public Rectangle Rectangle
{
get; public Rectangle {
{
return new Rectangle((int)Position.X, (int)Position.Y, _texture.Width, _texture.Height) 。
}
}
public string Text { get; set; }
public Button(Texture2D texture, SpriteFont font)。
{
_texture = texture;
_font = 字體。
TextColour = Color.White。
}
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)。
{
var color = Color.White;
spriteBatch.Draw(_texture, Rectangle, color);
if (!string.IsNullOrEmpty(Text))
{
var x = (Rectangle.X (Rectangle.Width / 2)) - (_font.MeasureString(Text).X / 2) 。
var y = (Rectangle.Y (Rectangle.Height / 2)) - (_font.MeasureString(Text).Y / 2) 。
//center the font within the button
spriteBatch.DrawString(_font, Text, new Vector2(x, y), TextColour)。
}
}
public override void Update(GameTime gameTime)
{
_previousMouse = _currentMouse;
_currentMouse = Mouse.GetState();
//sets location of the mouse to actual current position
if (_currentMouse.LeftButton == ButtonState.Released & _previousMouse.LeftButton == ButtonState.Pressed)
{
Click?.Invoke(this, new EventArgs())。
//if click event handler is != null ....use it
}
}
我設定了這些類來注冊我游戲中的一個按鈕。
在game1.cs中,我試圖添加以下內容來加載內容。
_spriteBatch = new SpriteBatch(GraphicsDevice)。
var randomButton = new Button(Content.Load<Texture2D>("Controls/Button"), Content.Load<SpriteFont>("Fonts/Font")
{
};
當執行這個時,我得到錯誤代碼CS0144 "無法創建一個實體或抽象型別或介面'Button'"
。在game1的頂部,我使用namespace.Controls,因為Button.cs位于一個名為Controls的檔案夾中。我們歡迎任何關于這個問題的幫助或建議。
uj5u.com熱心網友回復:
為什么Button是抽象的?,抽象型別不能用new關鍵字初始化,相反,它們的建構式被認為是抽象的,派生型別應該對它呼叫base(),如果可能的話,考慮不要抽象Button這個類(可能是指:如果你有任何抽象成員,比它不可能,否則,是它)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/320703.html
標籤:
上一篇:Chromium(V8)vs.Firefox(SpiderMonkey)在訪問未定義屬性時出錯
下一篇:點擊按鈕后移動到頂部
