c#扩展方法

扩展函数

  1. 实现IEnumerable接口
public IEnumerator<int> GetEnumerator()
        {
            //throw new NotImplementedException();

            yield return 1;
            yield return 2;
            yield return 3;
            yield return 4;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

2 扩展方法的使用

  • 扩展方法的类型以及类名都是静态的,提供外部调用,等于是一个全局类
  • 给指定的类扩展需要使用this关键字指定 参数就是类
    代码案例如下:
/*
     * 
     * 扩展方法  使用this -->指代那个实例化对象扩展方法
     */
   static class MyExMethods
    {
        public static int MyMax(this MyList list)
        {
            int max = int.MinValue;

            var e = list.GetEnumerator();
            while (e.MoveNext())
            {
                if (e.Current > max)
                {
                    max = e.Current;
                }
            }
            return max;
        }

        public static int MyCount(this MyList vs)
        {
            int sum = 0;

            var list = vs.GetEnumerator();
            /*foreach (var i in list.MoveNext())
            {
                 sum++;
            }*/
            while (list.MoveNext())
            {
                sum++;
            }
            return sum;
        }

        public static void ForEach<T>(this IEnumerable<T> source,Action<T> func)
        {
            foreach(var item in source)
            {
                func(item);
            }
        }

        public static void Print<T>(this IEnumerable<T> ts)
        {
            foreach (var item in ts)
            {
                Console.WriteLine(item);
            }
        } 

        //字符串转换
        public static int ToInt(this string s)
        {
            return int.Parse(s);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值