在'if'中检查多个条件的语法声明

本文关键字:条件 声明 语法 检查 if | 更新日期: 2023-09-27 17:49:49

情况如下:

if count items is either 0,1,5,7,8,9,10 then string = "string one"
if count items is either 2,3,4 then string = "string two"

我试过了(inside cs razor view)

@if (@item.TotalImages == 1 || 5 || 7 || 8 || 9 || 10)
{
   string mystring = "string one"
}

但是我得到了这个错误

操作符||不能应用于bool或int类型的操作数

在'if'中检查多个条件的语法声明

或者

var accepted = new HashSet<int>(new[] {1, 5, 7, 8, 9, 10});
@if (accepted.Contains(item.TotalImages))
{
   string mystring = "string one"
}

或操作符的语法错误。

改变。

@if (@item.TotalImages == 1 || @item.TotalImages == 5)
{
   string mystring = "string one"
}

In扩展方法可能是这种情况下的语法糖:

public static class CLRExtensions
{
    public static bool In<T>(this T source, params T[] list)
    {
        return list.Contains(source);
    }
}

所以基本上不用多个or operator,你可以简单地写:

@if (@item.TotalImages.In(1, 5, 7, 8, 9, 10)
{
}

仔细看看错误消息:

运算符||不能用于类型为boolint

的操作数

和你的代码:

@if (@item.TotalImages == 1 || 5)

你正在对bool (@item)对象应用||运算符。TotalImages == 1)和int(5)。"为或为5"没有意义。'False or 5'也不行

基本上,你所需要做的就是使运算符的两边都是布尔值。

@if (@item.TotalImages == 1 || @item.TotalImages == 5)

(当然)还有很多其他聪明的方法可以做到这一点,但这可能是最直接的。

如果你想检查所有这些可能性,你可能会用一个非常大的'if'语句结束。使用LINQ更简洁的方法是:

@if ((new List<int>{ 0, 1, 5, 7, 8, 9, 10 }).Contains(@item.TotalImages))
{
    string mystring = "string one"
}

这样,您可以更容易地查看和维护要检查的数字列表(或者,实际上从其他地方传递它们)。

在"||"之间必须是一个表达式,可以转换为布尔值(true/false):

@if (@item.TotalImages == 1 || @item.TotalImages == 5 || @item.TotalImages == 7 || @item.TotalImages == 8 || @item.TotalImages == 9 || @item.TotalImages == 10)
    {
       string mystring = "string one"
    }
@else @if(@item.TotalImages == 2 || @item.TotalImages == 3 || @item.TotalImages == 4)
    {
       string mystirng = "string two"
    }

我会使用一个开关:

@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.

的情况。