我会使用开关:
@switch (@item.TotalImages)
{
case 0:
case 1:
case 5:
case 7:
case 8:
case 9:
case 10:
s = "string one";
break;
case 2:
case 3:
case 4:
s = "string two";
break;
default:
throw new Exception("Unexpected image count");
}
奇怪的是,没有人推荐一本字典:
private string stringOne = "string one";
private string stringTwo = "string two";
private Dictionary<int, string> _map = new Dictionary<int, string>
{
{ 0, stringOne },
{ 1, stringOne },
{ 2, stringTwo },
{ 3, stringTwo },
{ 4, stringTwo },
{ 5, stringOne },
{ 7, stringOne },
{ 8, stringOne },
{ 9, stringOne },
{ 10, stringOne },
}
然后
@var s = _map[@item.TotalImages];
这种方法更容易看出,例如,您没有处理 TotalImages == 6 的情况。