简写的条件语句

问题描述:

我正在寻找一种方式来写是这样的:简写的条件语句

if (product.Category.PCATID != 10 && product.Category.PCATID != 11 && product.Category.PCATID != 16) { } 

在象下面这样一条捷径,这并不当然工作:

if (product.Category.PCATID != 10 | 11 | 16) { } 

那么,有没有速记方式完全可以做类似的事情?

+0

它在这个问题有了答案,以及:http://*.com/questions/9033/hidden-features-of-c/33384#33384 – Patrick

+0

@ LaserBeak:你最新的编辑改变你的问题**完全**!这甚至没有编译。 –

+0

@LaserBeak:发布答案后,很大程度上改变你的问题是非常糟糕的做法。 –

你可以使用一个扩展方法:

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 
} 

是 - 你应该使用一套:

private static readonly HashSet<int> FooCategoryIds 
    = new HashSet<int> { 10, 11, 16 }; 

... 

if (!FooCategoryIds.Contains(product.Category.PCATID)) 
{ 
} 

您可以使用列表或数组或基本上任何集合,当然 - 和小套的ID都不会有问题的,其你使用...但我会亲自使用HashSet来表明我真的只对“设置”感兴趣,而不是订购。

+0

有关HashSet的更多信息和用法,请看这里。 http://johnnycoder.com/blog/2009/12/22/c-hashsett/ –

你可以做这样的事情:

List<int> PCATIDCorrectValues = new List<int> {10, 11, 16}; 

if (!PCATIDCorrectValues.Contains(product.Category.PCATID)) { 
    // Blah blah 
} 

嗯......我想一个速记版本是if(true),因为如果PCATID == 10,这是= 11,= 16,所以!整个表达是true
PCATID == 11PCATID == 16也是如此。
对于任何其他数字,所有三个条件是true
==>你的表情将永远是true

其他的答案是唯一有效的,如果你真正的意思是:

if (product.Category.PCATID != 10 && 
    product.Category.PCATID != 11 && 
    product.Category.PCATID != 16) { } 

if (!new int[] { 10, 11, 16 }.Contains(product.Category.PCATID)) 
{ 
} 

using System.Linq加上t你的课程或.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 
    } 
}