基本C#对象与对象交互
我目前正在浏览各种资源,并试图学习C#OOP。我还没有经历过这方面的任何事情,但我尝试过对象与对象的交互。不幸的是,它没有按计划进行,我对应该引用哪些对象有点困惑。我想创建一个简单的攻击方法,降低另一个对象的运行状况,从而降低对象与对象交互的基础。代码如下:基本C#对象与对象交互,c#,oop,object,C#,Oop,Object,我目前正在浏览各种资源,并试图学习C#OOP。我还没有经历过这方面的任何事情,但我尝试过对象与对象的交互。不幸的是,它没有按计划进行,我对应该引用哪些对象有点困惑。我想创建一个简单的攻击方法,降低另一个对象的运行状况,从而降低对象与对象交互的基础。代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; nam
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;
}
}
}
}
代码根本不起作用。知道我做错了什么吗?谢谢你的帮助 你做了
日志-=-5
。但是日志不是一个数字。你需要参考狗的健康状况。您还需要将日志传递到LoseHealth()
函数中。将其更改为:
theDog.health -= 5;
这使用点表示法访问日志的运行状况
而且,函数嵌套在构造函数中。移动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;
}
}
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;
}
顺便说一句,不要只说“我的代码不工作”。解释它是如何不起作用的。如果有任何异常,请包含相关异常消息。dog类的代码有点混乱 攻击和健康方法在构造函数中 您只引用日志,而不引用运行状况和名称 看看这个
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提示:
这样更改攻击和恢复方法更有意义:
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;
}
}
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;
}
它怎么不起作用?它会爆炸吗?
LoseHealth
需要一个Dog
参数,这和Attack
都需要移出构造函数。