zoukankan      html  css  js  c++  java
  • C#扩展方法

    扩展方法(this参数)

    • 方法必须是公有的、静态的,即被public、static所修饰
    • 方法形参列表第一个,由this修饰
    • 必须由一个静态类(一般类名为SomeTypeExtension)来统一收纳对SomeType类型的扩展方法
    • 举例:LINQ方法

    没有扩展方法:

    class Program
    {
        static void Main(string[] args)
        {
            double x = 3.14159;
            // double 类型本身没有 Round 方法,只能使用 Math.Round。
            double y = Math.Round(x, 4);
            Console.WriteLine(y);
        }
    }

    有扩展方法后:

    class Program
    {
        static void Main(string[] args)
        {
            double x = 3.14159;
            // double 类型本身没有 Round 方法,只能使用 Math.Round。
            double y = x.Round(4);
            Console.WriteLine(y);
        }
    }
    
    static class DoubleExtension
    {
        public static double Round(this double input,int digits)
        {
            return Math.Round(input, digits);
        }
    }

     LINQ实例

    class Program
    {
        static void Main(string[] args)
        {
            var myList = new List<int>(){ 11, 12, 9, 14, 15 };
            //bool result = AllGreaterThanTen(myList);
            // 这里的 All 就是一个扩展方法
            bool result = myList.All(i => i > 10);
            Console.WriteLine(result);
        }
    
        static bool AllGreaterThanTen(List<int> intList)
        {
            foreach (var item in intList)
            {
                if (item <= 10)
                {
                    return false;
                }
            }
    
            return true;
        }
    }

    All 第一个参数带 this,确实是扩展方法。

  • 相关阅读:
    Cocos2d Box2D之动态刚体
    Cocos2d Box2D之简介
    Cocos2d-x之物理引擎
    Cocos2d-x之UI控件简介
    Cocos2d-x之数据的处理
    My First Django Project (3)
    My First Django Project (2)
    My First Django Project
    Python 学习笔记
    利用python scrapy 框架抓取豆瓣小组数据
  • 原文地址:https://www.cnblogs.com/Mr-Prince/p/12116699.html
Copyright © 2011-2022 走看看