zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
    111
  • 相关阅读:
    电脑快捷键
    方法
    运算符和表达式
    Java关键字和标识符
    字体和文本
    盒子模型
    css
    常用标签
    第一次课(上)
    出现次数最多的数字
  • 原文地址:https://www.cnblogs.com/zwj-199306231519/p/11716711.html
Copyright © 2011-2022 走看看