[英]How do I get a code block to run when a variable changes?
我正在编写一个小游戏的代码,所以很自然,我有很多变量,每当变化时都会做不同的事情。 我的问题是,是否有可能告诉我的代码在每次变量改变时运行某些代码行,以避免反复输入相同的行,一遍又一遍?
例:
Hero1.Health = 10;
Hero1.MaxHealth = 12;
ProgressBarHeroHealth1.Max = Hero1.MaxHealth;
ProgressBarHeroHealth1.Value = Hero1.Health;
如果我更改了英雄的健康状况,我希望进度条值随之自动更改,而不必在每次更改时将其写下来。
我不知道是否可能,或者我只是希望得到太多,所以我来找你答案。 任何信息将不胜感激。
您可以为控件编写扩展方法,例如
static class ExtensionMethods
{
static public void SetHealth(this ProgressBar control, Hero hero)
{
control.Max = hero.MaxHealth;
control.Value = hero.Health;
}
}
并称之为:
ProgressBarHeroHealth1.SetHealth(Hero1);
现在扩展方法很酷,但这就像使用它们的最愚蠢的方法。 如果控制类没有密封,更好的设计是编写一个合适的方法:
public class HealthBar : ProgressBar
{
public void SetHealth(Hero hero)
{
this.Max = hero.MaxHealth;
this.Value = hero.Health;
}
}
并以同样的方式调用它:
HealthBarHeroHealth1.SetHealth(Hero1);
(为了使其工作,您必须在您正在使用的任何UI平台中使用HealthBar而不是ProgressBar)。
但你知道什么会很酷吗? 更新自己的进度条。 嗯...也许如果它听了某种事件......
class HeroHealthBar : ProgressBar
{
protected readonly Hero _hero;
public HeroHealthBar(Hero hero) : base()
{
_hero = hero;
hero.HealthChanged += this.Hero_HealthChanged;
}
public void Hero_HealthChanged(object sender, EventArgs e)
{
this.Max = _hero.MaxHealth;
this.Value = _hero.Health;
}
}
当然,你需要一个提升事件的英雄课程......
class Hero
{
public event EventHandler HealthChanged;
public void SetHealth(int current, int max)
{
_health = current;
_maxHealth = max;
OnHealthChanged();
}
protected void OnHealthChanged()
{
if (HealthChanged != null) HealthChanged(this, EventArgs.Empty);
}
}
完成所有这些设置后,当您想要设置健康状况时,您所要做的就是写
_hero.SetHealth(current,max);
...将它设置在英雄身上并自动通知进度条以更新自己。
有可能的。 假设您有一个名为Hero的类,并且您希望在健康增加或减少时更改进度条颜色
Class Hero
{
Public String Name{get; set;}
Public Double health;
Public Double Health
{
get
{
return health;
}
set
{
//Here you can place a function which can easily check the value of health and work accordingly.
ProgressBarColorChange(value+health);
health = value;
}
}
Public void ProgressBarColorChange(double health)
{
//Color Change Fuction Implementation
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.