2

我正在用 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%")但我不太确定。

4

1 回答 1

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;
}
于 2013-08-08T11:58:22.783 回答