简体   繁体   English

是否在新的Mailmessage正文中声明?

[英]If statement inside a new Mailmessage body?

Quick question about new MailMessage body that I cant seem to find an answer to in google. 关于new MailMessage body快速问题,我似乎无法在Google中找到答案。

How can I make an if statement that checks if an element is visible and then takes the string in the element and applies it to the body? 我如何制作一条if语句来检查一个元素是否可见,然后将该元素中的字符串应用于正文?

mail.Body += "<b>" + D1ContactPanel.Visible ? "Subsidiary contacts: " : "" + "</b> " + D1ContactPanel.Visible ? D1ContactDDL.Text : "" + "</br></br>";

Edit: Visual studio says "Cannot implicitly convert type 'string' to 'bool'" 编辑:Visual Studio说“无法将类型'string'隐式转换为'bool'”

Enclose in brackets, like: 用括号括起来,例如:

mail.Body += "<b>" + (D1ContactPanel.Visible ? "Subsidiary contacts: " : "") + "</b> " + (D1ContactPanel.Visible ? D1ContactDDL.Text : "") + "</br></br>";

This will evaluate your condition and return appropriate string as a result which will be concatenated. 这将评估您的条件并返回适当的字符串作为连接结果。

If you miss out brackets, then it first tries to concatenate D1ContactPanel.Visible to "<b>" and then evaluate the condition which fails because it cannot evaluate the string. 如果错过了方括号,则它首先尝试将D1ContactPanel.Visible连接到“ <b>”,然后评估失败的条件,因为它无法评估字符串。 Hence the error "cannot convert string to boolean". 因此,错误“无法将字符串转换为布尔值”。

您需要添加一些括号,不仅为了进行编译,还为了开发人员的见解:)

mail.Body += "<b>" + (D1ContactPanel.Visible ? "Subsidiary contacts: " : "") + "</b> " + (D1ContactPanel.Visible ? D1ContactDDL.Text : "") + "</br></br>";
mail.Body += "<b>" + (D1ContactPanel.Visible ? "Subsidiary contacts: " : "") + "</b> " + (D1ContactPanel.Visible ? D1ContactDDL.Text : "") + "</br></br>";

Separate the string values from your boolean condition: 将字符串值与布尔条件分开:

mail.Body += @"<b>" + (D1ContactPanel.Visible ? "Subsidiary contacts: " : "") 
+ "</b> " + (D1ContactPanel.Visible ? D1ContactDDL.Text : "") 
+ "</br></br>";

Please, change your code from 请从

mail.Body += "<b>" + D1ContactPanel.Visible ? "Subsidiary contacts: " : "" + "</b> " + D1ContactPanel.Visible ? D1ContactDDL.Text : "" + "</br></br>";

to

mail.Body += "<b>" + (D1ContactPanel.Visible ? "Subsidiary contacts: " : "" )+ "</b> " + (D1ContactPanel.Visible ? D1ContactDDL.Text : "") + "</br></br>";

you can Enclose in brackets like other answers to avoid exception, but I think you don't need to check two times and make this code more readable as below 您可以像其他答案一样用括号括起来以避免出现异常,但是我认为您无需检查两次即可使此代码更具可读性,如下所示

if(D1ContactPanel.Visible)
   mail.Body += string.Format("<b>Subsidiary contacts: </b>{0}</br></br>", D1ContactDDL.Text);

then you can even move this string literals to constants or resources 那么您甚至可以将此字符串文字移到常量或资源中

你可以试试

mail.Body += string.Format("<b>{0}</b> {1}<br /><br />", D1ContactPanel.Visible ? "Subsidiary contacts: " : string.Empty, D1ContactPanel.Visible ? D1ContactDDL.Text : string.Empty);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM