Las*_*eak 4 c# if-statement c#-4.0
我正在寻找一种写这样的东西的方法:
if (product.Category.PCATID != 10 && product.Category.PCATID != 11 && product.Category.PCATID != 16) { }
Run Code Online (Sandbox Code Playgroud)
以下面的简写方式,当然不起作用:
if (product.Category.PCATID != 10 | 11 | 16) { }
Run Code Online (Sandbox Code Playgroud)
那么有什么简便方法可以做类似的事情吗?
是的 - 你应该使用一套:
private static readonly HashSet<int> FooCategoryIds
= new HashSet<int> { 10, 11, 16 };
...
if (!FooCategoryIds.Contains(product.Category.PCATID))
{
}
Run Code Online (Sandbox Code Playgroud)
当然,您可以使用列表或数组或基本上任何集合 - 对于小的ID集合,您使用哪个ID并不重要......但我个人会用a HashSet表示我真的只对" set-ness",而非订购.
您可以使用扩展方法:
public static bool In<T>(this T source, params T[] list)
{
return list.Contains(source);
}
Run Code Online (Sandbox Code Playgroud)
称之为:
if (!product.Category.PCATID.In(10, 11, 16)) { }
Run Code Online (Sandbox Code Playgroud)