1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace LinqToSql 8 { 9 /// <summary> 10 /// 如果引用第三方的类文件,可以给该类文件添加自己的扩展方法,逼格杠杠的 11 /// 12 /// 不能滥用 13 /// </summary> 14 public static class ExtendsShow 15 { 16 /// <summary> 17 /// 扩展方法:静态类里的静态方法,第一个参数类型前面加上this 18 /// </summary> 19 /// <param name="data">int? 表示可以添加具体值,也可以为空null</param> 20 /// <returns>data ?? -1: 表示如果给参数data赋值为null,那么返回-1,如果赋值为具体某个值,就返回赋值的结果</returns> 21 public static int ToInt(this int? data) 22 { 23 return data ?? -1; 24 } 25 26 /// <summary> 27 /// 该方法只能扩展第一个参数类型,不能扩展后面的 28 /// 给LamdaShow类进行扩展 29 /// </summary> 30 /// <param name="lamda"></param> 31 /// <param name="iParameter"></param> 32 /// <param name="sParameter"></param> 33 public static void ExtendLamdaShow(this LamdaShow lamda, int iParameter, string sParameter) 34 { 35 Console.WriteLine($"LamdaShow=={ iParameter}==={ sParameter }"); 36 } 37 } 38 }
上端主程序调用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace LinqToSql 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 //int类型调用扩展方法 13 int? data = null; 14 int? other = 2; 15 Console.WriteLine(ExtendsShow.ToInt(data)); 16 Console.WriteLine(other.ToInt()); 17 Console.ReadLine(); 18 19 //LamdaShow其他类调用扩展方法 20 new LamdaShow().ExtendLamdaShow(123, "张三"); 21 } 22 } 23 }
第三方类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace LinqToSql 8 { 9 public class LamdaShow 10 { 11 12 } 13 }