我有两个继承自同一个抽象类的类.我希望他们两个或至少一个人知道另一个人的特定属性的变化.这样做有什么简单的方法吗?我一直在尝试将变量移动到父类,但是这只创建了2个相同的变量,当我在第一个变量中创建对另一个类的引用时,同样的事情发生了.谢谢.
这就是我的代码:
public abstract class Animal
{
public int MovementSpeed;
public bool Death;
public string Feedback;
public bool DeerCaught;
public int tiredRate;
public virtual int Movement()
{
MovementSpeed = MovementSpeed - tiredRate;
return MovementSpeed;
}
public virtual string Print()
{
return Feedback;
}
}
public class Deer : Animal
{
public string hidden;
public string Foraging;
public int DeerCount;
public Deer()
{
this.DeerCount = 10;
this.DeerCaught = false;
this.MovementSpeed = 10;
this.tiredRate = 2;
}
public void Hide()
{
if (Hunting)
{
Feedback = "The deer is hiding.";
if (DeerCount > 0)
{
Print();
}
}
else
{
//Forage();
}
}
public void Forage()
{
if (!Hunting)
{
Feedback = "The deer is searching for food.";
if (DeerCount > 0)
{
Print();
}
}
else
{
//Hide();
}
}
}
public class Wolf : Animal
{
public int Hunger;
public bool Hunting;
public Wolf()
{
this.Hunting = false;
this.Hunger = 10;
this.MovementSpeed = 10;
this.tiredRate = 1;
}
public bool Hunt()
{
if (Hunger < 5)
{
Hunting = true;
Feedback = "The wolf is searching for his next meal.";
if (DeerCaught == true)
{
Hunger++;
}
else
{
Hunger--;
}
return Hunting;
}
else
{
Hunting = false;
Feedback = "The wolf decides to rest.";
Hunger--;
return Hunting;
}
}
public void Die()
{
if (Hunger < 0)
{
Death = true;
Feedback = "The wolf has lost the hunt.";
}
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试Hunting在基类中设置为静态,但是当我运行每个类的方法时,我最终得到了两个不同版本的'Hunting'.
如果这是作为一个模拟,那么当狼在狩猎时不会告诉鹿,它必须找出来.这里的模拟是有一些方法,鹿可以查询狼的存在(类似于Deer.LookForWolves(),然后检查Hunting每个狼的属性的价值.这将需要某种控制器类,代表世界.
class World
{
public static List<Animal> Animals = new List<Animal>();
//...
}
class Deer : Animal
{
//...
bool IsSafe()
{
return LookForWolves().All(wolf => !wolf.Hunting);
}
List<Wolf> LookForWolves()
{
return World.Animals.OfType<Wolf>();
}
//...
Run Code Online (Sandbox Code Playgroud)
或者,您可以引用World作为每个成员Animal,通过构造函数传入.这取决于您,并取决于您是否需要拥有多个World对象,每个对象都有不同的Animals 列表.
| 归档时间: |
|
| 查看次数: |
1799 次 |
| 最近记录: |