if语句匹配多个值 [英] if statements matching multiple values
本文介绍了if语句匹配多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何简单的方法来if语句写这个?
Any easier way to write this if statement?
如果(价值== 1 ||值== 2)
例如......在SQL你可以说其中(1,2)
而不是,其中value = 1或值= 2的价值
。
For example... in SQL you can say where value in (1,2)
instead of where value=1 or value=2
.
我在找的东西,将与任何基础类型...字符串,整数等工作。
I'm looking for something that would work with any basic type... string, int, etc.
推荐答案
如何
if (new[] {1, 2}.Contains(value))
这是一个黑客,但:)
It's a hack though :)
或者,如果你不介意创建自己的扩展方法,您可以创建以下内容:
Or if you don't mind creating your own extension method, you can create the following:
public static bool In<T>(this T obj, params T[] args)
{
return args.Contains(obj);
}
和您可以使用它是这样的:
And you can use it like this:
if (1.In(1, 2))
:)
这篇关于if语句匹配多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文