是否有更好的简单 if 语法,分配变量
我的代码基本上在一种情况下分配一个变量,在另一种情况下分配不同的变量。有没有更简洁、更高效的方法?
即,不占用那么多线路。或者这是最好的方法?
if (ViewBag.Date != RoomBooking.StartDateTime.Date || ViewBag.DayPlannerStartTime * 12 > (Int32)RoomBooking.StartDateTime.TimeOfDay.TotalMinutes / 5)
{
StartBlock = ViewBag.DayPlannerStartTime * 12;
}
else
{
StartBlock = ((Int32)RoomBooking.StartDateTime.TimeOfDay.TotalMinutes / 5);
}
I have code that basically assigns a variable in one case, else a different in another. Is there a neater way that is more efficient?
I.e., not taking up so many lines. Or is this the best way?
if (ViewBag.Date != RoomBooking.StartDateTime.Date || ViewBag.DayPlannerStartTime * 12 > (Int32)RoomBooking.StartDateTime.TimeOfDay.TotalMinutes / 5)
{
StartBlock = ViewBag.DayPlannerStartTime * 12;
}
else
{
StartBlock = ((Int32)RoomBooking.StartDateTime.TimeOfDay.TotalMinutes / 5);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许是这样的(可以说它更整洁,但绝对具有相同的效率):
编辑:您也可以稍微优化条件。我怀疑您的 DayPlannerStartTime 以秒为单位,如果我是对的,您可以按以下方式重写比较(我只是将
>
运算符的两个操作数除以12,TotalMinutes
除以 5*12 就变成了TotalHours
):Maybe this (it's arguably neater, but definitely has the same efficiency):
EDIT: You can slightly optimize the condition as well. I suspect that your
DayPlannerStartTime
is expressed in seconds, and if I'm right you can rewrite the comparison the following way (I just divided both operands of the>
operator by 12, andTotalMinutes
divided by 5*12 becameTotalHours
):是的,您可以使用 ?: 运算符 创建单个表达式,如果条件为 true,则计算结果为第一个表达式,否则计算为第二个表达式:
Yes, you can use the ?: operator to create a single expression that will evaluate to the first expression if the condition is true, or else to the second expression: