需要帮助防止无限循环.属性设定 [英] Need help preventing infinite loop. Setting of Properties
问题描述
所以我有一个颜色选择器.用户可以使用RGB或HSB选择颜色.每个值都有滑块/属性.例如,当用户设置红色时,我将计算HSB值以反映新的颜色值.当用户设置色相时,将从HSB值重新计算RGB值.但是,看到那里有一个循环.设置RGB时,到目前为止,必须重新计算HSB值,但这还意味着HSB值将发生变化,从而导致RGB值再次被更新.我认为这是问题所在,但是我该如何解决?
So I have a color picker. Users can pick colors using RGB or HSB. There are sliders/properties for each value. When user sets Red for example, I will calculate HSB values to reflect new color value. When user sets Hue, the RGB value will be recalculated from the HSB values. But see there's a loop there. When I set RGB it must recalculate HSB values, ok so far, but it also means that HSB values will change causing RGB values to be re updated again. I think this is where the problem is but how can I fix this?
我使用的一种可能的解决方案是标志,虽然不是很可读,但是它可以工作.基本上,当我设置属性时,我还设置了一个标志来表示我正在设置一个值
One possible solution I used was flag, not very readable tho, but it works. Basically, when I set properties, I also set a flag to signify I am setting a value
public float Hue {
get { return _hue; }
set
{
if (_hue == value)
return;
CurrentlySetting = (CurrentlySetting.HasValue) ? CurrentlySetting : ColorType.HSB;
_hue = value;
NotifyPropertyChanged("Hue");
NotifyPropertyChanged("Color");
RecalculateRGB();
CurrentlySetting = (CurrentlySetting == ColorType.HSB) ? null : CurrentlySetting;
}
}
重新计算"值时,我会检查并确保我当前未设置这些值
When I "Recalculate" Values, I check for that and ensure I am not currently setting them
protected void RecalculateRGB(Color color = new Color())
{
if (CurrentlySetting == ColorType.RGB) // prevent stackoverflow
return;
if (color == new Color())
color = HSBColorHelper.FromAHSB(255, Hue, Saturation, Brightness);
Red = color.R;
Green = color.G;
Blue = color.B;
}
不是很直接,我还是更喜欢@Marc Gravell的解决方案
Not very straight forward, I still prefer @Marc Gravell's, solution
推荐答案
我将所有setter都调用到相同的内部代码中:
I would have all the setters call into the same inner code:
public byte R {
get {return r;}
set { SetRGB(value, G, B); }
}
public byte G {
get {return g;}
set { SetRGB(R, value, B); }
}
etc-内部的 SetRGB
方法仅与字段(而不是属性)通信,包括您需要的任何HSB字段;所以没有递归.显然,您可能还需要 SetHSB
-再次设置 all 字段(不调用任何属性设置器).
etc - and that inner SetRGB
method only talks to the fields (not the properties), including any HSB fields you need; so no recursion. You might also want a SetHSB
, obviously - again, setting all the fields (not calling into any of the property setters).
这篇关于需要帮助防止无限循环.属性设定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!