避免过长的if语句

 
 

我在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 ExpandedBlockStart.gif View Code
 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扩展方法

http://home.cnblogs.com/group/topic/47711.html

转载于:https://www.cnblogs.com/pg-love/archive/2011/07/15/2106961.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值