我在IF中经常用到一个方法,用来简化if (x == a || x == b || x ==c) 这样对同一个对象进行多次相等性比较的方法:
public static bool In<T>(this T val, params T[] values)(3.0)
{
return values.Contains(val);
}
public static bool In(T val, params T[] values)(2.0)
{
return Array.Equals(T values,Predicate<T> match);
}
这个方法还可以进一步扩展,比如添加IEqualityComparer<T>等等。
用法: if (x.In(a,b,c)) (2.0不能扩展)
下面的只是2.0的实现(不能扩展)
![ContractedBlock.gif](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 static void Main(string[] args)
2 {
3 int[] number=new int[]{5679,4,36,67976,124,235,453,436,6589,0,5,6,346,457,34,3642};
4
5 for(int i=0;i<number.Length;++i)
6 {
7 int a = number[i];
8 if (a == 0 || a == 4||a==5)
9 {
10 Console.WriteLine(a);
11 }
12
13
14 }
15 //简化
16 int var=0;
17 bool flag=In(var,number);
18 Console.WriteLine(flag);
19
20 Console.ReadKey();
21 }
22 public static bool In(int val, params int[] values)
23 {
24 return Array.Exists(values,delegate(int var){return var==val;});
25 }
3.0的扩展方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StaticMethod;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int x=4;
bool flag = x.In(1, 2, 3,4);
Console.WriteLine(flag); //True
Console.ReadKey();
}
}
}
namespace StaticMethod
{
public static class StaticClass
{
public static bool In(this int val, params int[] values)
{
return Array.IndexOf(values, val) != -1;
}
}
}
http://msdn.microsoft.com/zh-cn/library/bb311042(v=VS.90).aspx
3.0扩展方法