2012-07-28 30 views
1

我使用C#編寫了一個簡單的遊戲,以幫助我學習基本的面向對象的概念。C#可以繼承的方法或屬性使用派生類成員而不創建新方法嗎?

在下面的代碼:

class entity 
    { 
    int hp; 
    string name; 

    public entity() 
    { 
     hp = 1; 
     name = "entity"; 
    } 

    public string status() 
    { 
     string result; 
     result=name + "#" + " HP:" + hp; 
     return result; 
    } 






    class dragon : entity 
    { 

    new public string name; 
    new int hp; 


    public dragon() 
    { 
     hp = 100; 
     name = "Dragon"; 

    } 
} 

我由對象 「龍」 這樣

dragon mydragon = new dragon(); 

的問題是用下面的代碼:

mydragon.status(); 

該返回一個字符串,但帶有「名稱」和「hp」的實體 cla ss對象(即hp = 1,name = entity)。

我想讓這個返回龍對象的值(hp = 100,name = dragon)。我不確定我做錯了什麼,但看起來很簡單。

擺弄和掙扎小時後,唯一的解決辦法我能來是簡單地複製粘貼& 的狀態()法在龍類。但我相信有更好的方法來做到這一點。

許多在此先感謝。

回答

6

簡單裝飾字段hpnameentityprotected訪問修飾符。有了它,他們也可以在dragon課程中使用,並且您不必重新定義它們。您可以保留dragon的構造函數,因爲它將在entity類的構造函數之後運行,從而覆蓋其字段的值。

它可能看起來如下:

public class Entity 
{ 
    protected int hp; 
    protected string name; 

    public Entity() 
    { 
     hp = 1; 
     name = "entity"; 
    } 

    public override string ToString() 
    { 
     string result = name + "#" + " HP:" + hp; 
     return result; 
    } 
} 

public class Dragon : Entity 
{ 
    public Dragon() 
    { 
     hp = 100; 
     name = "Dragon"; 
    } 
} 

按照慣例,在C#中的類名稱開頭大寫字母。此外,對於像返回類的表示字符那樣的東西,ToString()方法通常會被重寫。

+0

驚人的答覆!我非常喜歡這個+你命名類的「禮節」的技巧:)我非常確定,對於像我自己一樣從C#開始的任何人來說,這將非常方便。從來不知道整個訣竅是使用受保護的訪問修飾符。 – Xenosteel 2012-07-28 22:24:58

0

我會在每個繼承類中添加virtual關鍵字entity類到status方法和override

編輯:尼古拉的代碼看起來也很公平,如果你想使用的只是.ToString()代替Status()

0

做以下修改......

class entity 
    { 
    protected int hp; 
    protected string name; 
... 


class dragon : entity 
    { 

    // new public string name; - you're creating new variables hiding the base ones 
    // new int hp;    - ditto. Don't need them 
.... 
+0

完美!這正好解決了問題。非常感謝您的回覆:) – Xenosteel 2012-07-28 22:27:18

相關問題