简体   繁体   English

三元运算符; 这个语法有什么问题?

[英]Ternary operator; What is wrong with this syntax?

I'm trying to create a MailMessage, and I'm getting the following error... 我正在尝试创建一个MailMessage,我收到以下错误...

 Cannot implicitly convert type 'string' to 'bool' 

This is my init statement: 这是我的初始声明:

MailMessage msg = new MailMessage("DoNotReply@optoma.com",
                      myTbl.Rows[i]["Requester"].ToString().Trim(),
                      subject, 
                      "Dear " + myTbl.Rows[i]["Ship_Attention"].ToString() + ",<br/><br/>" +
                      body + "<br/>Your ISO ID is " + myTbl.Rows[i]["ISO_ID"].ToString() + 
                      (Convert.ToInt32(myTbl.Rows[i]["EmailType"]) == 1) ? 
                          ("<br/>Tracking Number: " + myTbl.Rows[i]["Tracking_No"].ToString()) : 
                          ("") + "<br/><br/>Please examine the loaned items for this transaction:<br/><br/>" +
                      sw.ToString());

I'm trying to add to the string at runtime based on a boolean expression. 我试图在运行时基于布尔表达式添加到字符串。 Why can't I do this? 为什么我不能这样做? Am I not doing it right? 我做得不对吗?

string + (true | false) ? "somestring" : "anotherstring" + string

the ? 的? : operator has very low precedence. :运算符的优先级非常低。 Put it in parenthesis and I think you'll resolve your issue. 把它放在括号中,我想你会解决你的问题。

((true|false)?"somestring":"anotherstring")

When you have string + (bool)?"somestring":"anotherstring" + string the + gets evaluated before the ? 当你有string + (bool)?"somestring":"anotherstring" + string +之前得到的评估? , so you need parentheses: ,所以你需要括号:

string + ((bool)?"somestring":"anotherstring") + string

just cleaning it up a wee bit.... and you won't run into operator precedence problems so much 只是清理一下......你不会遇到操作符优先级问题

  void SendMessage(DataRow  row, string subject, string body, string sw)
    {
        var to = row["Requester"].ToString().Trim();
        var isoId = row["ISO_ID"].ToString();
        var attention = row["Ship_Attention"].ToString();
        var emailType = Convert.ToInt32(row["EmailType"]);
        var message = (emailType == 1) ? ("<br/>Tracking Number: " + row["Tracking_No"]) : ("");
        MailMessage msg = new MailMessage("DoNotReply@optoma.com",
                  to,
                  subject, 
                  string.Format("Dear {0},<br/><br/>{1}<br/>Your ISO ID is {2}{3}<br/><br/>Please examine the loaned items for this transaction:<br/><br/>{4}",
                                attention, body, isoId, message, sw));
    }

The precedence isn't what you expect -- + is being evaluated first. 优先级不是您所期望的 - +正在首先进行评估。 Your code should be in the form: 您的代码应采用以下形式:

string + (true|false ? "somestring" : "anotherstring") + string

For your specific example: 对于您的具体示例:

MailMessage msg = new MailMessage("DoNotReply@optoma.com", myTbl.Rows[i]["Requester"].ToString().Trim(),
subject, "Dear " + myTbl.Rows[i]["Ship_Attention"].ToString() + ",<br/><br/>" +
body + "<br/>Your ISO ID is " + myTbl.Rows[i]["ISO_ID"].ToString() + (Convert.ToInt32(myTbl.Rows[i]["EmailType"]) == 1 ? ("<br/>Tracking Number: " + myTbl.Rows[i]["Tracking_No"].ToString()) : ("")) + "<br/><br/>Please examine the loaned items for this transaction:<br/><br/>" +
sw.ToString());

Note that this is a very long expression and should probably be broken down into several statements to make it more readable and maintainable. 请注意,这是一个非常长的表达式,应该可以分解为几个语句,以使其更具可读性和可维护性。

The additive oprator (+) has higher priority than conditional (?:) as indicated here: http://msdn.microsoft.com/en-us/library/aa691323%28v=vs.71%29.aspx . 添加操作符(+)的优先级高于条件(?:),如下所示: http//msdn.microsoft.com/en-us/library/aa691323%28v=vs.71%29.aspx

Therefore you need to put parenthesis around the whole condition: 因此,您需要在整个条件周围加上括号:

string + ((true|false)?"somestring":"anotherstring") + string

I suggest you to divide your code into more lines, introduce some temporary variables and use string.format() to make it look clener. 我建议你将代码分成更多行,引入一些临时变量并使用string.format()使其看起来更清晰。 Finding errors in clean code is much easier. 在干净的代码中查找错误要容易得多。

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

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