zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    }
  • 相关阅读:
    v-bind绑定属性
    vue 第二次学习笔记 v-once v-html
    P4428-[BJOI2018]二进制【树状数组,set】
    P5180-[模板]支配树
    《架构之美》阅读笔记一
    Python基础04----条件控制
    Tensorflow2.0笔记33——Keras 来搭建神经网络的“八股”套路
    每周总结
    架构漫谈阅读笔记01
    Tensorflow2.0笔记32——卷积神经网络
  • 原文地址:https://www.cnblogs.com/kanekiken/p/7566600.html
Copyright © 2011-2022 走看看