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,确实是扩展方法。

  • 相关阅读:
    Spark集群安装与配置
    Kafka集群的安装和部署
    Sqoop的安装和验证
    Zookeeper与HBase的安装
    Hive的安装
    在Eclipse中开发MapReduce程序
    HDFS基本命令与Hadoop MapReduce程序的执行
    Hadoop环境部署
    Java基础(十七)日志(Log)
    Java基础(十六)断言(Assertions)
  • 原文地址:https://www.cnblogs.com/Mr-Prince/p/12116699.html
Copyright © 2011-2022 走看看