2014-06-08 5 views
-1

저는 현재 다양한 리소스를 통해 C# OOP을 배우려고합니다. 나는 아직 그것에 대해 아무 것도 배우지 않았지만 나는 객체 대 객체 상호 작용에 대해 생각해 봤다. 불행하게도 그것은 계획에 가지 않았고, 내가 참조해야했던 어떤 물건에 대해 약간 혼란스러워했다. 나는 객체와 객체의 상호 작용을 근본적으로 이해하기 위해 다른 객체의 건강을 감소시키는 간단한 공격 방법을 만들고 싶었다. 코드는 다음과 같습니다.기본 C# 개체 대 개체 상호 작용

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은 숫자가 아닙니다. 개 건강을 참조해야합니다. theDogLoseHealth() 함수에 전달해야합니다. 이를 다음으로 변경하십시오.

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

개 클래스의 코드가 엉망입니다.

공격 및 LoseHealth 메서드는 에서의 생성자입니다.

상태 및 이름을 참조하는 대신 사용자는 theDog만을 참조하십시오.

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; 
}