简体   繁体   English

三元最佳实践

[英]Ternary Best Practice

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>
}

And before I write lots of code like this, I wanted to know if this is a good way of doing this. 在编写大量这样的代码之前,我想知道这是否是实现此目的的好方法。

Thus the question is, in .NET is there a better framework way of doing this, or is the Ternary method fine 因此,问题是,在.NET中是否有更好的框架方法可以执行此操作,或者三元方法是否还可以

The premise is obviously 前提显然是

  • 0 records = I found no people 0条记录=我没有人
  • 1 record = I found 1 person 1条记录=我找到1个人
  • 2+ records = I found 2 people 2条以上记录=我发现2个人

In my opinion it is absolutely fine to use the Ternary conditional operator for this kind of condition. 在我看来,将Ternary条件运算符用于这种条件绝对是很好的。

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. 有经验的开发人员无需考虑即可理解它,但是如果您想让初学者更容易理解它,则也可以使用ifelse构造。

But I would use Any() as @I4V mentioned in the comment. 但是我将使用Any()作为注释中提到的@ I4V。

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>
}

If your doing it in a few places, an extension method would solve both your problems (readability & simplified code) 如果您在几个地方这样做,扩展方法将同时解决您的问题(可读性和简化代码)

public static string PersonCountString(this IEnumerable<Person> personList)
{
    var count = personList.Count();
    return String.Format("{0} {1}", count > 0 ? count : "no",
                                    count == 1 ? "person" : "people");
}
...
I found (@Model.PersonCountString())

To answer your question: no, I find that oneliner not readable, it reads like @(() 0 ? "" : .().()) @(.() == 1 ? "" : "") to me, not to mention the multiple calls to .Count() . 要回答您的问题:不,我发现oneliner不可读,对我来说就像@(() 0 ? "" : .().()) @(.() == 1 ? "" : "") ,更不用说对.Count()的多次调用了。

You could create a (shared) helper method like this: 您可以创建一个(共享的)辅助方法,如下所示:

string GetCountWithDescription(int count, 
                               string singleItemDescription, 
                               string multipleItemsDescription)
{
    switch (count)
    {
        case 0:
            return "no " + multipleItemsDescription;
        case 1:
            return "1 " + singleItemDescription;
        default:            
            return count + " " + multipleItemsDescription;
    }
}

Reusable too, so you can stick it in a separate file so it won't clutter your code, and you can simply call it in from every view like this: 也可以重复使用,因此您可以将其粘贴到一个单独的文件中,以免使代码混乱,并且可以从每个视图中简单地调用它,如下所示:

@GetCountWithDescription(Model.Count(), "person", "people")

What do you try to achieve? 您想达到什么目的? Better readability or faster code (development)? 更好的可读性或更快的代码(开发)? If the aim is for better readability, then I suggest to keep the ternary operation inside strings, for example: 如果目标是提高可读性,那么我建议将三元运算保留在字符串中,例如:

string modelCountStr = Model.Count() == 0 ? "no" : Model.Count().ToString(); string modelPluralStr = Model.Count() == 1 ? "person" : "people";

Considering you will have to use Count() if any users are present: 考虑到如果存在任何用户,则必须使用Count()

@{ 
    var count = Model.Count();
}

I found @(count == 0 ? "no" : count) @(count == 1 ? " person" : " people")

Another way to make it more readable would be to opt for a solution where there are as few or ideally zero conditionals involved, if possible. 使其更具可读性的另一种方法是选择一种解决方案,其中尽可能少地或理想地涉及零条件。

This is my take: 这是我的看法:

@{ 
    var count = Model.Count(); 
}
I found @string.Format(new[] { "no people", "{0} person", "{0} people"} [Math.Min(count, 2)], count)

Arguably Math.Min is responsible for some kind of branching, but I think this is much easier to understand. 可以说Math.Min负责某种分支,但是我认为这更容易理解。

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

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