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

  • 相关阅读:
    【二分】Pair of Topics
    【Windows】制作登录界面
    【Windows】制作文本框
    【windows】制作幸运“Tiger”机
    【python】函数
    SPOJ 3267 DQUERY
    CF 570D Tree Requests
    UVa 11809 Floating-Point Numbers
    Luogu P5098 Cave Cows 3
    GHOJ 428 未出现的子串
  • 原文地址:https://www.cnblogs.com/Mr-Prince/p/12116699.html
Copyright © 2020-2023  润新知