C#扩展方法

1.满足扩展方法的要求:

  (1)必须在一个非潜逃,非泛型的静态类中定义。

  (2)被扩展方法至少有一个参数。

  (3)第一个参数必须使用this关键字修饰,不可使用其他修饰符修饰。

  (4)参数不能是指针类型。

2.例子:

namespace text
{
    public static class Expand
    {
        public static int ExpandMethod(this IEnumerable<int> source)
        {
            if (source == null) return 0;
            else
            {
                int sum = 0;
                bool flag = false;
                foreach (int item in source)
                {
                    if (!flag)
                    {
                        sum += item;
                        flag = true;
                    }
                    else
                    {
                        flag = false;
                    }
                }
                return sum;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>() { 1, 2, 3, 4, 5 };
    //第一种调用方法
            int temp = Expand.ExpandMethod(list);
    //第二种调用方法
    int temp = list.ExpandMethod();
            Console.WriteLine(temp);

            Console.ReadKey();
        }
    }
}
posted @ 2019-10-21 22:19  zwj鹿港小镇  阅读(133)  评论(0编辑  收藏  举报