如果对同一变量使用两个不同的值进行推断

问题描述 投票:-1回答:2

我必须允许上传两种不同类型的图像尺寸图片的宽度可以为370或602

如何使用if语句使用图像宽度370 or 602来检查它。

如果图像宽度正确,那么可以,否则我删除文件。

以下代码始终失败,即使其中一个维度不匹配也是如此。我如何在下面允许任意一个尺寸

using System;

    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("Hello World");

            int imgW = 370; // assuming image width is 370

             if (imgW != 370 || imgW != 602)
                {
                 Console.WriteLine("One");
                }
            else
            {
                Console.WriteLine("Two");
            }

        }
    }
c#
2个回答
1
投票

您可以创建允许宽度的集合,以使代码更具可读性和可扩展性:

var allowedWidths = new[]{ 370, 602 };
if(allowedWidths.Contains(imgW))
{
    // upload
}
else
{
    // delete
}

具有单个值比较:

if(imgW == 370 || imgW == 602)
{
    // upload
}
else
{
    // delete
}

1
投票

根据您所说的内容:

如何使用if语句使用370或602的图像宽度来检查它。

您需要的是==运算符,以允许任意一个尺寸:

if (imgW == 370 || imgW == 602)
© www.soinside.com 2019 - 2024. All rights reserved.