2014-06-08 57 views
-1

我目前正在瀏覽各種資源並試圖學習C#OOP。我還沒有經過任何東西,但我有一個對象與對象交互。不幸的是,它沒有去計劃,我對我應該引用的對象有些困惑。我想創建一個簡單的攻擊方法,以減少另一個對象的運行狀況,以便獲得對象與對象交互的基礎知識。代碼如下:基本的C#對象vs對象的交互

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication7 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Dog milo = new Dog("Sparky"); 
      Dog ruffles = new Dog("Ruffles"); 
      milo.Attack(ruffles); 
      Console.ReadLine(); 
     } 
    } 
    class Dog 
    { 
     public string name { get; set; } 
     public int health = 100; 


     public Dog(string theName) 
     { 
      name = theName; 


      public void Attack(Dog theDog) 
      { 
       Console.WriteLine("{0} attacks {1}.", this.name, theDog); 
       LoseHealth(theDog); 
      } 

      public void LoseHealth() 
      { 
       Console.WriteLine("{0} loses health!", theDog); 
       theDog -= 5; 
      } 
     } 
    } 

} 

該代碼根本不起作用。任何想法,我做錯了什麼?謝謝你的幫助。

+0

問題是什麼? – SLaks

+0

它不起作用。 – user2925800

+2

** **如何不起作用?它爆炸了嗎? – SLaks

回答

0

你做了theDog -= -5。但theDog不是一個數字。你需要參考狗的健康狀況。您還需要將theDog傳遞給LoseHealth()函數。將其更改爲:

theDog.health -= 5; 

這使用點符號來訪問theDog的健康狀況。

但是,您的函數也嵌套在構造函數中。移動Attack()LoseHealth(),以便它們在類中,而不在構造函數體中。你應該得到這樣的事情:

class Dog 
    { 
    public string name { get; set; } 
    public int health = 100; 


    public Dog(string theName) 
     { 
      name = theName;    
     } 
    public void Attack(Dog theDog) 
      { 
       Console.WriteLine("{0} attacks {1}.", this.name, theDog); 
       LoseHealth(theDog); 
      } 

    public void LoseHealth(Dog theDog) 
      { 
       Console.WriteLine("{0} loses health!", theDog); 
       theDog.health -= 5; 
      } 
    } 

順便說一句,不要只是說「我的代碼不工作」。解釋它如何不起作用。如果有任何相關的異常消息,請加入。

1

狗類的代碼有點搞砸了。

The Attack and LoseHealth methods are in the constructor。

而不是提及健康和名稱,你只能引用狗。

看一看這個

class Dog 
{ 
    public string name { get; set; } 
    public int health = 100; 


    public Dog(string theName) 
    { 
     name = theName; 
    } 

    public void Attack(Dog theDog) 
    { 
     Console.WriteLine("{0} attacks {1}.", this.name, theDog.name); 
     LoseHealth(theDog); 
    } 

    public void LoseHealth(Dog theDog) 
    { 
     Console.WriteLine("{0} loses health!", theDog.name); 
     theDog.health -= 5; 
    } 
} 

額外OO提示:

它會更有意義改變攻擊和LoseHealth方法是這樣的:

public void Attack(Dog theDog) 
{ 
    Console.WriteLine("{0} attacks {1}.", this.name, theDog.name); 
    theDog.LoseHealth(5); 
} 

public void LoseHealth(int damage) 
{ 
    Console.WriteLine("{0} loses health!", name); 
    this.health -= damage; 
}