我尝试在 C# 中创建 RGB 中的颜色类,颜色值(红色、绿色、蓝色)必须在 [0,1] 范围内。
这是我的代码
public class ColorRGB
{
private ColorRGB(double _red, double _green, double _blue)
{
Red = _red;
Green = _green;
Blue = _blue;
}
public static ColorRGB ColorRGB_RGBModel(double _red, double _green, double _blue)
{
return new ColorRGB(_red, _green, _blue);
}
public static ColorRGB ColorRGB_CMYModel(double _cyan, double _magenta, double _yellow)
{
var _red = 1 - _cyan;
var _green = 1 - _magenta;
var _blue = 1 - _yellow;
return new ColorRGB(_red, _green, _blue);
}
public ColorRGB AddRGB(ColorRGB _secondColor)
{
return ColorRGB_RGBModel(this.Red + _secondColor.Red, this.Green + _secondColor.Green, this.Blue + _secondColor.Blue);
}
public ColorRGB SubtractRGB(ColorRGB _secondColor)
{
return ColorRGB_RGBModel(this.Red - _secondColor.Red, this.Green - _secondColor.Green, this.Blue - _secondColor.Blue);
}
public double Red {
get { return red; }
private set { red = red < 0 ? 0 : (red > 1 ? 1 : value); }
}
public double Green
{
get { return green; }
private set { green = green < 0 ? 0 : (green > 1 ? 1 : value); }
}
public double Blue
{
get { return blue; }
private set { blue = blue < 0 ? 0 : (blue > 1 ? 1 : value); }
}
public double Cyan
{
get { return cyan; }
private set { cyan = cyan < 0 ? 0 : (cyan > 1 ? 1 : value); }
}
public double Magenta
{
get { return magenta; }
private set { magenta = magenta < 0 ? 0 : (magenta > 1 ? 1 : value); }
}
public double Yellow
{
get { return yellow; }
private set { yellow = yellow < 0 ? 0 : (yellow > 1 ? 1 : value); }
}
private double red;
private double green;
private double blue;
private double cyan;
private double magenta;
private double yellow;
}
}
但是当我尝试创建此类的一个实例并尝试将颜色值(红色、贪婪、蓝色)设置为超出范围 [0, 1] 时,我的检查red = red < 0 ? 0 : (red > 1 ? 1 : value);
和其他检查都不起作用。
有人可以解释一下为什么会发生这种情况以及如何解决吗?