三元最佳实践 [英] Ternary Best Practice
问题描述
我有一点code,虽然简单或许不能立即为它做什么显而易见的。
I have a bit of code, that while simple perhaps isn't immediately obvious as to what it does.
I found @(Model.Count() == 0 ? "no" : Model.Count().ToString()) @(Model.Count() == 1 ? "person" : "people")
@foreach (var item in Model) {
<div>@item.Name at @item.Email</div>
}
和之前我写的很多code这样的,我想知道这是否是这样做的一个很好的方式。
And before I write lots of code like this, I wanted to know if this is a good way of doing this.
因此,问题是,在.NET中是有这样做的更好的框架的方法,或者是三元法细
Thus the question is, in .NET is there a better framework way of doing this, or is the Ternary method fine
在premise显然
- 0记录=我发现没有人
- 1纪录=我发现1人
- 2+记录=我发现2人
推荐答案
在我看来,这是精绝使用三元
有条件的运营商这种状况。
In my opinion it is absolutely fine to use the Ternary
conditional operator for this kind of condition.
有经验的开发人员了解它,而不考虑它,但如果你想,以方便阅读对于初学者来说,你也可以使用如果
和其他
结构。
Developers with experience understand it without thinking about it, but if you want to make it easy readable for beginners, you can also use an if
and else
construct.
不过,我会用任何()
作为@ I4V在注释中。
But I would use Any()
as @I4V mentioned in the comment.
I found @(Model.Any() ? Model.Count().ToString() : "no") @(Model.Count() == 1 ? "person" : "people")
@foreach (var item in Model) {
<div>@item.Name at @item.Email</div>
}
这篇关于三元最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!