C# 扩展方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//扩展方法
namespace extension_method
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> arr=new List<int>(){1,2,3,4,5,6};
            //计算数组中下标为奇数的所有项之和
            int jsum=arr.JSum();
            Console.WriteLine("奇数之和为{0}", jsum);
            Console.Read();
        }
    }
    /// <summary>
    /// 求数组中奇数索引和扩展方法
    /// </summary>
    public static class List_extension
    {
        public static int JSum(this IEnumerable<int> source)
        {
            if (source==null)
            {
                throw new ArgumentNullException("数组为空");
            }
            int jsum = 0;
            bool flag = false;
            foreach (int current in source)
            {
                if (!flag)
                {
                    jsum += current;
                    flag = true;
                }
                else
                {
                    flag = false;
                }
                
            }
            return jsum;
        }
    }
}

扩展方法:

1.此方法必须是一个静态方法

2.此方法必须放在静态类中

3.此方法的第一个参数必须以this开头,并且指定此方法是扩展自哪个类型

4.此方法

posted @ 2017-07-27 13:11  LBO.net  阅读(130)  评论(0编辑  收藏  举报
//返回顶部