条件语句的缩写
本文关键字:缩写 语句 条件 | 更新日期: 2023-09-27 18:09:27
我正在寻找一种写这样东西的方法:
if (product.Category.PCATID != 10 && product.Category.PCATID != 11 && product.Category.PCATID != 16) { }
用下面这样的简写方式,当然不起作用:
if (product.Category.PCATID != 10 | 11 | 16) { }
那么,有没有速记的方法来做类似的事情呢?
是-您应该使用一个集合:
private static readonly HashSet<int> FooCategoryIds
= new HashSet<int> { 10, 11, 16 };
...
if (!FooCategoryIds.Contains(product.Category.PCATID))
{
}
当然,您可以使用列表、数组或基本上任何集合,对于小的ID集,使用哪一个并不重要。。。但我个人会用HashSet
来表明我真的只对"集合性"感兴趣,而不是对排序感兴趣。
您可以使用一个扩展方法:
public static bool In<T>(this T source, params T[] list)
{
return list.Contains(source);
}
并称之为:
if (!product.Category.PCATID.In(10, 11, 16)) { }
这不完全是一个快捷方式,但可能对你来说是正确的。
var list = new List<int> { 10, 11, 16 };
if(!list.Contains(product.Category.PCATID))
{
// do something
}
嗯。。。我认为缩写版本应该是if(true)
,因为如果PCATID
==10,它就是!=11和!=16,所以整个表达式是true
PCATID == 11
和PCATID == 16
也是如此
对于任何其他数,所有三个条件都是true
===>您的表达式将始终为true
。
其他答案只有在你真的这么想的时候才有效:
if (product.Category.PCATID != 10 &&
product.Category.PCATID != 11 &&
product.Category.PCATID != 16) { }
您可以这样做:
List<int> PCATIDCorrectValues = new List<int> {10, 11, 16};
if (!PCATIDCorrectValues.Contains(product.Category.PCATID)) {
// Blah blah
}
if (!new int[] { 10, 11, 16 }.Contains(product.Category.PCATID))
{
}
将using System.Linq
添加到类的顶部,否则.Contains
将生成编译错误。
使用switch
:简化
switch(product.Category.PCATID) {
case 10:
case 11:
case 16: {
// Do nothing here
break;
}
default: {
// Do your stuff here if !=10, !=11, and !=16
// free as you like
}
}