对于已经定义好的类,对其进行拓展方法
下面我们给出对于String类和Int类的拓展方法的举例:
static class Demo3 { public static void Test1() { string str = "夜空中最亮的星"; str.TestMethod(); } public static void Test2() { int num = 88; num.TestMethod(); } public static int TestMethod(this int name) { Console.WriteLine("老子是拓展方法"); return 110; } static void Main(string[] args) { Test2(); } }
***我们注意的是拓展的类必须是静态类,而且方法也应该是静态的,
应该使用一些关键字表明这个方法是类的拓展方法,this int name,拓展的是Int类。
Linq查询用到一些拓展方法
class Demo4 { List<Employ> empArray; List<EmpLevel> empLevelArray; List<Employ> empResult; public Demo4() { empArray = new List<Employ>(); empLevelArray = new List<EmpLevel>(); empResult = new List<Employ>(); //雇员信息初始化 empArray.Add(new Employ(1, "梅西", 32, 10)); empArray.Add(new Employ(2, "内马尔", 27, 8)); empArray.Add(new Employ(3, "卡瓦尼", 32, 5)); empArray.Add(new Employ(4, "德布劳内", 32, 6)); empArray.Add(new Employ(5, "马内", 32, 2)); empArray.Add(new Employ(6, "卡卡", 32, 9)); //雇员等级初始化 empLevelArray.Add(new EmpLevel(1,1,"一级实习",3000)); empLevelArray.Add(new EmpLevel(2, 2, "二级见习", 5000)); empLevelArray.Add(new EmpLevel(3, 3, "三级菜鸟", 8000)); empLevelArray.Add(new EmpLevel(4, 3, "四级新手", 10000)); empLevelArray.Add(new EmpLevel(5, 4, "五级员工", 30000)); empLevelArray.Add(new EmpLevel(6, 5, "六级老手", 50000)); } public void Test1() { //var result = empArray.Where(Method); where里面的参数的委托 var result = empArray.Where(e => e.LevelNum > 6); #lambda表达式,委托简化写法 foreach (var item in result) { Console.WriteLine(item); } } public bool Method(Employ emp) { if (emp.LevelNum > 6) { return true; } else { return false; } } static void Main(string[] args) { Demo4 obj = new Demo4(); obj.Test1(); } }