IF电池电量声明

时间:2013-08-08 11:54:29

标签: c# conditional-statements

我正在使用C#进行语音识别程序,我编写了几行代码,当我说“电池电量”时会回复当前的电池电量。

if (e.Result.Text.ToLower() == "battery level")
        {
            System.Management.ManagementClass wmi = new System.Management.ManagementClass("Win32_Battery");
            var allBatteries = wmi.GetInstances();
            String estimatedChargeRemaining = String.Empty;

            foreach (var battery in allBatteries)
            {
                estimatedChargeRemaining = Convert.ToString(battery["EstimatedChargeRemaining"]);
            }

            JARVIS.Speak("The Power Level Is At: " + estimatedChargeRemaining + "% sir");
            return;
        }

其中我想创建另一个 if语句,以提醒我电池电量是否已降低低于25%。如何才能做到这一点?我猜它会像“if estimatedChargeRemaining < 25 then JARVIS.Speak("Warning, Battery level has dropped below 25%")”,但我不太确定。

1 个答案:

答案 0 :(得分:2)

我不确定battery["EstimatedChargeRemaining"]返回什么格式,但似乎可以将其转换为int而不是字符串。

int batteryLevel = Convert.ToInt32(battery["EstimatedChargeRemaining"]);
if(batteryLevel < 25)       
   JARVIS.Speak("Warning, Battery level has dropped below 25%");

然后您可以稍后在

上使用该batteryLevel变量
JARVIS.Speak("The Power Level Is At: " + batteryLevel.ToString() + "% sir");

不确定是否有意,但您的foreach循环意味着您只会获得allBatteries中最后一个值的电池信息。之前的所有值都将被覆盖。

编辑评论(您应该添加错误处理)

if (e.Result.Text.ToLower() == "battery level")
{
    System.Management.ManagementClass wmi = new System.Management.ManagementClass("Win32_Battery");
    var allBatteries = wmi.GetInstances();
    //String estimatedChargeRemaining = String.Empty;
    int batteryLevel = 0;

    foreach (var battery in allBatteries)
    {
        batteryLevel = Convert.ToInt32(battery["EstimatedChargeRemaining"]);
    }

    if(batteryLevel < 25)       
       JARVIS.Speak("Warning, Battery level has dropped below 25%");
    else //Guessing you want else
       JARVIS.Speak("The Power Level Is At: " + batteryLevel.ToString() + "% sir");
    return;
}