我有一個Cube類。立方體可以被約束,使得width=height=length
。我已經編寫了這個功能,但正如你所看到的,我的代碼導致了循環/無限循環 - the width sets the height which sets the width which sets the height and so on
。相關屬性:如何避免無限循環
如何讓我的Cube類受到限制並避免這種無限循環?我唯一的解決方案是使用布爾變量propagate
(見下文)?
public class Cube {
public bool isConstrained {get; set;} // if constrained then width=height=length
// Causes a circular problem. How can I avoid this? Maybe create a variable private bool propagate = false; ??
public double width
{
get { return width; }
set
{
width = value;
if (isConstrained)
{
height = value;
length = value;
}
}
}
public double height
{
get { return height; }
set
{
height = value;
if (isConstrained)
{
width = value;
length = value;
}
}
}
public double length
{
get { return length; }
set
{
length = value;
if (isConstrained)
{
height = value;
width = value;
}
}
}
}
我唯一的解決辦法是這樣的:
private bool propagate = true;
public double length
{
get { return length; }
set
{
length = value;
if (isConstrained && propagate)
{
propagate = false;
height = value;
width = value;
propagate = true;
}
}
}
爲什麼不是私人領域? – Mephy
@Mephy我不太明白這將如何解決我的問題?我的目標是讓人們能夠從外部(公共)設置立方體屬性,但是當立方體受到限制時,我設置了寬度,我希望高度和長度也會改變(以寬度值)。 –