给类添加扩展方法
1、定义一个类Service
public class Service { private string _name; public string Name { get { return _name; } set { _name = value; } } private string _age; public string Age { get { return _age; } set { _age = value; } } public Service(string name, string age) { this.Age = age; this.Name = name; } }
2、给类Service添加扩展方法
public static class KuoService { //给Service类添加扩展方法,使用this关键字 public static void SayHi(this Service strs) { Console.WriteLine("...{0}...{1}", strs.Name, strs.Age); } }
3、扩展方法调用
Service ser = new Service("xsl","26"); ser.SayHi(); Console.ReadKey();
原文地址:http://www.cnblogs.com/laimeier/p/3804154.html