【问题标题】:Convert Multiple if condition into Ternary Operator将多个 if 条件转换为三元运算符
【发布时间】:2019-10-08 05:07:31
【问题描述】:

我想将以下条件转换为三元

if (!string.IsNullOrEmpty(objModel.Status))
{
    if (objModel.Status == "0")
    {
        Model.Sort = "Result1";
    }
    else if (objModel.Status == "8")
    {
        Model.Sort = "Result2";
    }
    else 
    {
        Model.Sort = "Result3"; 
    }
}

我已经尝试如下,但它上升到 if 而 else not else if

Model.Sort = !string.IsNullOrEmpty(Model.Status) 
    ? (Model.Status == "0" ? Retult1 : string.Empty) 
    : string.Empty;

【问题讨论】:

  • 听起来很简单,你试过这样做吗?此外,这听起来是个糟糕的主意——用三元条件运算符重写的这段代码看起来很糟糕。
  • 你这样做有什么问题?您尝试了什么,尝试的解决方案遇到了什么问题?
  • 您的最终版本是“Result3”吗?目前您的第二个if 部分是不必要的。
  • “我想将以下条件转换为三元”请不要。不要为了在文件中节省几行(可用)空间而将代码转换为难以阅读的内容。
  • 此外,您的代码的原始版本无法转换为三元,因为如果字符串为空/空,则不会发生任何事情。三元必须始终返回一个值。

标签: c# ternary-operator


【解决方案1】:

为简化保留一个局部变量

var x = objModel.Status;
if (string.IsNullOrEmpty(x))
{
    Model.Sort = x=="0" ? "Result1" :
        x=="8" ? "Result2" :
            "Result3";
}

【讨论】:

    【解决方案2】:

    你可以有这样的三元运算符

    a ? b : c ? d : e
    

    得到这个:

    if (a) {
      b
    }
    else if (c) {
    {
      d
    }
    else {
      e
    }
    

    在你的情况下

    objModel.Status == "0" ? Model.Sort = "Result1" : objModel.Status == "8" ? Model.Sort = "Result2" : Model.Sort = "Result2";
    

    我希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      您可以使用这样的三元运算符编写代码:

      Model.Sort = string.IsNullOrEmpty(objModel.Status)    //    if (string.IsNullOrEmpty(Status))
          ? Model.Sort                                      //        Model.Sort = Model.Sort;
          : objModel.Status == "0"                          //    else if (Status == "0")
              ? "Result1"                                   //        Model.Sort = "Result1";
              : objModel.Status == "8"                      //    else if (Status == "8")
                  ? "Result2"                               //        Model.Sort = "Result2";
                  : "Result3";                              //    else Model.Sort = "Result3";
      

      其中第一个条件代表if条件,然后作为比较的:运算符之后的每个语句代表一个else if,最后最后一个:之后的结果代表最终else任务。

      第一个条件是一种“虚拟”条件(因为如果它为真,则什么都不会真正改变*),但如果我们想在三元运算中包含IsNullOrEmpty 检查,则它是必需的,因为三元运算符必须返回truefalse 情况下的值。

      我不确定虚拟分配是否会得到优化,或者是否在那种“虚拟”情况下调用了 setter。如果调用了 setter,那么这可能会产生与原始代码不同的效果,具体取决于 setter 代码的作用。

      【讨论】:

        猜你喜欢
        • 2017-08-26
        • 2012-02-12
        • 2021-02-22
        • 1970-01-01
        • 2021-11-28
        • 2021-03-17
        • 2021-07-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多