C#扩展方法

扩展方法:

首先是一种方法,他可以用来扩展已定义类型中的方法成员

 

扩展方法定义规则:

①扩展方法必须在一个非嵌套、非泛型的静态类中定义

②他至少要有一个参数

③第一个参数必须加上this关键字作为前缀(第一个参数类型也称为扩展类型,即指方法对这个类型的扩展)

④第一个参数不能使用任何其他修饰符(如不能使用ref,out等修饰符)

⑤第一个参数的类型不能是指针类型

 

扩展方法图示:

 

示例代码:

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

namespace 扩展方法
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> source = new List<int> { 1, 2, 3, 4, 5, 6, 3 };
            int jsum = source.Jsum();
            Console.WriteLine("jsum:" + jsum);
            Console.Read();
        }
    }
    public static class ListExten
    {
        //定义扩展方法
        //同public static int Jsum(this List<int> source)
        public static int Jsum(this IEnumerable<int> source)
        {
            if (source == null)
            {
                throw new ArgumentException("输入数组为空");
            }
            int jsum = 0;
            //flag变量用作下标,以计算所有技术下标之和
            bool flag = false;
            foreach (int current in source)
            {
                if (!flag)
                {
                    jsum += current;
                    flag = true;
                }
                else
                {
                    flag = false;
                }
            }
            return jsum;
        }

    }
}

 运行效果:

 

posted @ 2016-10-24 19:57  抢囡囡糖未遂  阅读(221)  评论(0编辑  收藏  举报