C#中的扩展方法

扩展方法
对类的扩展有许多方法,如果有类的源代码,继承是给对象添加功能最好的方法。如果没有源代码,就可以使用扩展方法。

public class Student
{
    public int age=10;
    public static class StudentExtention
    {
        public static void AddAge(this Student stu,int i)
        {
            stu.age += i;
        }
     }
}        

扩展的方法必须是静态方法,必须放在一个静态类中。对于扩展方法,第一个参数是要扩展的类型,必须放在this关键字后面。在扩展方法中,可以访问所扩展类型的所有公共方法和属性。

调用扩展方法时,必须是实例对象调用。
如果扩展方法与类中的某个方法的签名相同,扩展方法就从来不会被调用,类中已有的实例方法优先。

原文地址:https://www.cnblogs.com/hwy2014/p/4211031.html