You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# if语句报错预期"{"却得到"(" 湿度检测发邮件功能开发求助

C#湿度告警邮件功能报错排查结果

你遇到的编译错误是C#和Python的语法差异导致的,核心问题如下:

  • 每个if条件判断后你连续写了2个左大括号,C#要求if对应的执行块仅需一对大括号包裹即可,多余的大括号破坏了语法结构,是触发括号匹配错误的直接原因
  • 现有逻辑存在边界遗漏:当湿度值正好等于2时,两个if分支都不会触发,可根据实际需求调整阈值逻辑

修正后可正常运行的代码

/// Adding time (In progress. Lines 2, 3, 12, 26)

// 湿度过高发送邮件
if (MoistureValue > 2) 
{
    using (var smtpClient = new SmtpClient("smtp.gmail.com")
    {
        Port = 587,
        Credentials = new NetworkCredential("testemail@email.com", "RandomPasswordRandomNumber"),
        EnableSsl = true,
    })
    {
        smtpClient.Send("exampleemail@email.com", "My name", "Plant Moisture", "Your plant is above its reccomended moisture go check on it!.");
    }
}
// 湿度过低发送邮件
else if (MoistureValue < 2) 
{
    using (var smtpClient = new SmtpClient("smtp.gmail.com")
    {
        Port = 587,
        Credentials = new NetworkCredential("testemail@email.com", "RandomPasswordRandomNumber"),
        EnableSsl = true,
    })
    {
        smtpClient.Send("exampleemail@email.com", "My Name", "Plant Moisture", "Your plant is a little dry, go water it!");
    }
}
// 湿度等于2属于正常区间无需处理,可根据需求自行调整阈值

补充说明

  • 代码中新增using关键字包裹SmtpClient实例,会在代码执行完成后自动释放网络资源,避免后台残留无效连接
  • 第二个if调整为else if可减少冗余判断,如果你有独立的阈值判定需求也可以改回两个独立的if分支
  • 若需要将湿度等于2的情况归入某一类告警,直接修改判断符号即可,例如将<2改为<=2就会把等于2的场景归为干燥告警

内容的提问来源于stack exchange,提问作者LoganS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 16:54:03