C#方法拓展

作用:

扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。

要求:

1.拓展方法必须是在一个非嵌套、非泛型的静态类中定义。
2.他至少有一个参数。
3.第一个参数必须加上this关键字作为前缀(第一个参数类型被称为拓展类型,即之方法对这个类型进行拓展)
4.第一个参数不能使用任何其他的修饰符(包括ref,out等)
5.第一个参数类型不能是指针类型

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

namespace _11_拓展方法
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> source = new List<int>() { 1, 2, 3, 4, 5 };
            //简单的调用方式  
            int res = source.JSum();
            Console.WriteLine("第一种方式调用结果:"+res);
            //第二种调用方式
            int res2 = ListExtem.JSum(source);
            Console.WriteLine("第一种方式调用结果:" + res2);
            Console.ReadKey();
        }
    }

    public static class ListExtem
    {
        public static int JSum(this IEnumerable<int> source)
        {
            if (source == null)
            {
                throw new ArgumentException("输入的参数数组为空。。");
            }
            int jSum = 0;
            bool isFlag = false;
            foreach (int current in source)
            {
                if (!isFlag)
                {
                    jSum += current;
                    isFlag = true;
                }
                else
                {
                    isFlag = false;
                }
            }
            return jSum;
        }
    }
}
原文地址:https://www.cnblogs.com/kanekiken/p/7566600.html