Заменитель объекта класса - C#
Формулировка задачи:
Привет! Подскажите пожалуйста почему так работает?
Рабочий вариант:
Нерабочий вариант:
Основной метод:
Class Unit
{
public int health;
public int damage;
public void Hit(Unit Target)
{
Target.health = Target.health - damage;
Console.WriteLine();
Console.WriteLine("{0}", Target.health);
}
}Class Unit
{
public int health;
public int damage;
public void Hit()
{
health = health - damage;
Console.WriteLine();
Console.WriteLine("{0}", health);
}
}static void Main()
{
Unit hero = new Unit();
Unit enemy = new Unit();
hero.health = 100;
hero.damage = 10;
enemy.health = 50;
enemy.damage = 5;
Console.WriteLine("{0}, {1}", hero.health, hero.damage);
Console.WriteLine();
Console.WriteLine("{0}, {1}", enemy.health, enemy.damage);
hero.Hit(enemy);
Console.ReadKey();
}Решение задачи: «Заменитель объекта класса»
textual
Листинг программы
class Unit
{
private int health;
private int damage;
public int Health
{
set
{
health = value;
}
get
{
return health;
}
}
public int Damage
{
set
{
damage = value;
}
get
{
return damage;
}
}
public void Hit(int getDamage)
{
health -= getDamage;
Console.WriteLine("\n{0}", health);
}
public Unit(int health, int damage)
{
this.health = health;
this.damage = damage;
}
}
class Program
{
static void Main(string[] args)
{
Unit hero = new Unit(100, 10);
Unit enemy = new Unit(50, 5);
Console.WriteLine("Hero (health-{0}), with {1} damage", hero.Health, hero.Damage);
Console.WriteLine("\nEnemy (health-{0}), with {1} damage", enemy.Health, enemy.Damage);
hero.Hit(enemy.Damage);
Console.ReadKey();
}
}