因此,这是一小段C#代码,模仿不倒翁拨盘。
此处的主程序- 实例化两个翻转开关-其中一个引用第一个。 这个想法是当Tumbler x完成旋转“重置”并触发一个事件时,该事件触发Tumbler y致动并增加
class Program
{
public static Tumbler x;
public static Tumbler y;
static void Main(string[] args)
{
x = new Tumbler(10);
y = new Tumbler(x, 20);
while (true)
{
Console.WriteLine(x.Teeth + " " + y.Teeth);
x.Actuate();
Console.ReadKey();
}
}
}
这是tumbler类-两个事件处理程序,在填充LinkedTumbler属性时会自动订阅该事件处理程序。
它可以按预期工作,直到事件被触发为止-并且“程序由于堆栈溢出而终止”
public class Tumbler
{
private const int DEFAULT_TEETH_MAX = 6;
private const int DEFAULT_LOWEST_TEETHVAL = 1;
private Tumbler linkedtumbler;
private int current_Teeth;
private int max_Teeth;
private const int DEFAULT_TEETH = 1;
public event EventHandler MaxTriggered;
public event EventHandler MinTriggered;
public Tumbler() : this(DEFAULT_TEETH_MAX)
{
}
public Tumbler(int maxTeethValue, int currentTeeth = DEFAULT_TEETH)
{
MaxTeeth = maxTeethValue;
Teeth = currentTeeth;
}
public Tumbler(Tumbler tbLink, int maxTeethValue, int currentTeeth = DEFAULT_TEETH) : this(maxTeethValue, currentTeeth)
{
LinkedTumbler = tbLink;
}
public int Teeth
{
get
{
return this.current_Teeth;
}
private set
{
if(value < DEFAULT_LOWEST_TEETHVAL)
{
if(MinTriggered != null)
MinTriggered(this, new EventArgs());
this.current_Teeth = MaxTeeth;
}
else if (value <= MaxTeeth)
{
this.current_Teeth = value;
}
else
{
if (MaxTriggered != null)
MaxTriggered(this, new EventArgs());
this.current_Teeth = DEFAULT_LOWEST_TEETHVAL;
}
}
}
public int MaxTeeth
{
get
{
return this.max_Teeth;
}
private set
{
this.max_Teeth = value;
}
}
public Tumbler LinkedTumbler
{
get
{
return linkedtumbler;
}
private set
{
linkedtumbler = value;
if (linkedtumbler.MaxTriggered == null)
linkedtumbler.MaxTriggered += Linkedtumbler_MaxTriggered;
}
}
private void Linkedtumbler_MaxTriggered(object sender, EventArgs e)
{
linkedtumbler.Actuate();
}
public void Actuate()
{
Teeth++;
}
public void ReverseActuate()
{
Teeth--;
}
}
答案 0 :(得分:1)
在调用x.Actuate()
的某个时刻,它命中了:
if (MaxTriggered != null)
MaxTriggered(this, new EventArgs());
this.current_Teeth = DEFAULT_LOWEST_TEETHVAL;
区域;所以-它通过MaxTriggered
调用事件,该事件基本上是y.Linkedtumbler_MaxTriggered;
;这会直接返回到linkedtumbler.Actuate();
,实际上是x.Actuate();
。并回想一下您尚未设置this.current_Teeth = DEFAULT_LOWEST_TEETHVAL;
(我们还没有完成),所以什么都没有改变-我们将继续在堆栈中做同样的事情-潜水直到爆炸。