基本C#对象与对象交互

时间:2014-06-08 16:52:10

标签: c# oop object

我目前正在浏览各种资源并尝试学习C#OOP。我还没有经历过任何事情,但我对象与对象互动有所了解。不幸的是,它没有去计划,我对我应该引用的对象有点困惑。我想创建一个简单的攻击方法,减少另一个对象的健康状况,只是为了获得对象与对象交互的基础知识。这是代码:

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

}

代码根本不起作用。对我做错了什么的想法?谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

狗类的代码有点混乱。

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

答案 1 :(得分: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;
            }
    }

顺便说一下,永远不要只说“我的代码不起作用”。解释它是如何工作的。如果有,请包含相关的异常消息。