扩展方法
1、扩展方法所在的类必须与原类在相同的命名空间中;
2、方法的第一个参数为:this+原类型+对象名;
3、扩展方法所在的类其类名可任意;
例如:
①原始类 People.cs
namespace ConsoleApp1.Tools { public class People { private int _age; public int Age { get { return _age; } set { _age = value; } } private string _name; public string Name { get { return _name; } set { _name = value; } } public void ShowPeople() { Console.WriteLine($"Name:{Name};Age:{Age}."); } } }
②扩展方法所在的类 Person.cs
namespace ConsoleApp1.Tools { public static class Person { public static void AddAge(this People people,int age) { people.Age += age; } } }
③调用 Program.cs
Using ConsoleApp1.Tools; namespace ConsoleApp1 { class Program { static void Main(string[] args) { People p = new People() { Age = 10,Name="yolanda" }; p.ShowPeople(); p.AddAge(2); // 对象成功访问扩展方法 p.ShowPeople(); } } }