我正在尋找一種方式來寫是這樣的:簡寫的條件語句
if (product.Category.PCATID != 10 && product.Category.PCATID != 11 && product.Category.PCATID != 16) { }
在象下面這樣一條捷徑,這並不當然工作:
if (product.Category.PCATID != 10 | 11 | 16) { }
那麼,有沒有速記方式完全可以做類似的事情?
我正在尋找一種方式來寫是這樣的:簡寫的條件語句
if (product.Category.PCATID != 10 && product.Category.PCATID != 11 && product.Category.PCATID != 16) { }
在象下面這樣一條捷徑,這並不當然工作:
if (product.Category.PCATID != 10 | 11 | 16) { }
那麼,有沒有速記方式完全可以做類似的事情?
你可以使用一個擴展方法:
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
來表明我真的只對「設置」感興趣,而不是訂購。
有關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 == 11
和PCATID == 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
}
}
它在這個問題有了答案,以及:http://stackoverflow.com/questions/9033/hidden-features-of-c/33384#33384 – Patrick
@ LaserBeak:你最新的編輯改變你的問題**完全**!這甚至沒有編譯。 –
@LaserBeak:發佈答案後,很大程度上改變你的問題是非常糟糕的做法。 –