当我们想对一个类增加方法时,通常是在原有的类上进行修改,但C#3为我们提供了扩展方法,扩展方法可以不需要对原有类进行修改就能为其添加方法

    • 扩展方法:为静态类里面的静态方法,第一个参数类型(需要扩展的类)签名加上this
    • 用途:可以不修改类,增加方法
    • 缺陷:
      • 如果扩展的方法实例中也有,优先调用实例方法
      • 扩展基类型可能导致子类覆盖 ```csharp class Student { string name{get; set;}; }

    public static class EXtendMethod { public static void Sing(this Student student) { }

    1. //不要扩展object!扩展基类型慎重,子类都有此方法
    2. public static int Length(this object ivalue)
    3. {
    4. return ivalue == null ? 0 : ivalue.ToSting.Length;
    5. }

    } ```