ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
答案 0 :(得分:4)
(列出的代码来自ASP.Net MVC 5应用程序中的脚手架ManageController
)
虽然使用嵌套的if语句可以实现相同的结果:
if (message == ManageMessageId.ChangePasswordSuccess)
ViewBag.StatusMessage = "Your password has been changed."
else if (message == ManageMessageId.SetPasswordSuccess)
ViewBag.StatusMessage = "Your password has been set."
...
或切换声明
switch (message)
case ManageMessageId.ChangePasswordSuccess:
ViewBag.StatusMessage = "Your password has been changed.";
break;
case ManageMessageId.SetPasswordSuccess:
ViewBag.StatusMessage = "Your password has been set.";
break;
...
以链式方式使用条件运算符有利于避免重复分配ViewBag.StatusMessage
,因为它允许投影必须具有相同类型的结果,因此允许单个赋值。它还不鼓励在if
或switch
语句中编码的副作用行为。
编辑,其他替代方案
如果排列的数量变得非常大,我会选择Dictionary
查找模式将ManageMessageId
值映射到要在ManageController的Viewbag
中设置的字符串,因为这会减少比较次数以匹配适当的密钥:
private static readonly IDictionary<ManageMessageId, string> _messageDictionary
= new Dictionary<ManageMessageId, string>
{
{ManageMessageId.ChangePasswordSuccess, "Your password has been changed."},
{ManageMessageId.SetPasswordSuccess, "Your password has been set."},
// ...
};
等效映射代码将是简单的(仅使用条件运算符) - ManageMessageId
是一个枚举:
public async Task<ActionResult> Index(ManageMessageId? message)
{
ViewBag.StatusMessage = (message.HasValue)
? _messageDictionary[message.Value]
: "";