if ((Tempereture >= MaxTempertureValue) || (Co >= MaxCoValue) || (Fire == 1)) { // 如果输入数据高于设置的值,小灯开始红色闪烁 customButton.light.Fill = Brushes.Red; var animation = new DoubleAnimation(0, 1, TimeSpan.FromSeconds(0.5)); animation.AutoReverse = true; animation.RepeatBehavior = RepeatBehavior.Forever; customButton.light.BeginAnimation(Ellipse.OpacityProperty, animation); } if(Fire == 2) { customButton.light.Fill = Brushes.Yellow; var animation = new DoubleAnimation(0, 1, TimeSpan.FromSeconds(0.5)); animation.AutoReverse = true; animation.RepeatBehavior = RepeatBehavior.Forever; customButton.light.BeginAnimation(Ellipse.OpacityProperty, animation); } else { // 如果输入数据低于或等于设置的值,小灯颜色变为绿色 customButton.light.Fill = Brushes.Green; customButton.light.BeginAnimation(Ellipse.OpacityProperty, null); }优化代码
时间: 2024-01-27 15:06:13 浏览: 67
基于STM32芯片温度传感器,芯片温度测量(源码+相关教程)-电路方案
可以考虑将两个 if 语句合并成一个,使用 else if 的方式判断 Fire 的值,这样可以减少代码冗余。同时,可以将重复的动画代码封装成一个方法,减少代码重复。
代码优化后如下:
```
if (Temperature >= MaxTemperatureValue || Co >= MaxCoValue || Fire == 1)
{
SetLightColor(customButton.light, Brushes.Red);
}
else if (Fire == 2)
{
SetLightColor(customButton.light, Brushes.Yellow);
}
else
{
SetLightColor(customButton.light, Brushes.Green);
}
private void SetLightColor(Ellipse light, SolidColorBrush color)
{
light.Fill = color;
var animation = new DoubleAnimation(0, 1, TimeSpan.FromSeconds(0.5));
animation.AutoReverse = true;
animation.RepeatBehavior = RepeatBehavior.Forever;
light.BeginAnimation(Ellipse.OpacityProperty, animation);
}
```
阅读全文