如何用三元运算符替换if else块? [英] How to replace if else block with ternary operator?

查看:212
本文介绍了如何用三元运算符替换if else块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int Lookup_Id = _Imain_lookupService.AddEditDelete(ent.LookUp);
            if (Lookup_Id < 0)
            {
                TempData["err"] = strErrorMsg;
            }
            else
            {
                TempData["msg"] = strSuccessMsg;
            }

推荐答案

?: 运营商 [ ^ ]如果您想将一个值或另一个值返回到变量,则非常有用。

例如
The ?: ternary operator[^] is useful if you want to return one value or the other to a variable.
For e.g.
x != 0.0 ? Math.Sin(x) / x : 1.0;





在你的情况下,使用三元运算符是没有意义的。



In your case, it does not make sense to use a ternary operator.


这里没有充分的理由改变你的代码:



1.您的代码不适合使用三元运算符而不修改其结构。



2.使用三元运算符会导致性能下降:[ ^ ]
There's no good reason to change your code here:

1. your code is not suitable for using the ternary operator without modification of its structure.

2. there is a performance penalty for using the ternary operator: [^]


如前所述,在你的情况下不可能这样做。为什么?因为您使用两个单独的对象来添加值。要使用它,你需要更改对象( TempData 中的项目),我会这样写:

As already mentioned, it is impossible to do that in your case. Why? Because you are using two separate objects to add the value to. To use it, you need to change the objects (items in your TempData), I would write it like this:
int Lookup_Id = _Imain_lookupService.AddEditDelete(ent.LookUp);
if (Lookup_Id < 0)
{
    TempData["Message"] = strErrorMsg;
}
else
{
    TempData["Message"] = strSuccessMsg;
}



所以,现在你可以使用三元运算符来最小化代码。


So, now you can surely use the ternary operator to minimize the code.

int Lookup_Id = _Imain_lookupService.AddEditDelete(ent.LookUp);

// Apply the condition and now save the value in the same object.
TempData["Message"] = (Lookup_Id < 0) ? strErrorMsg : strSuccessMsg;



现在可以使用了。我建议您再次阅读MSDN文档,?:运算符(C#参考) [ ^ ]


这篇关于如何用三元运算符替换if else块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆