#region 扩展方法 3.0
{
//普通方法调用
Student student = new Student()
{
Id = 1,
Name = "Mr.zhang",
Age = 25,
ClassId = 2
};
student.Study();
//扩展方法调用
ExtendMethod.StudyPractise(student); //
student.StudyPractise(); //扩展方法;看起来跟实例方法调用方式一样
}
#endregion
/// <summary>
/// 扩展方法:静态类里面的静态方法,第一个参数类型前面加上this
/// </summary>
public static class ExtendMethod
{
///如果需要一个方法满足需求,那就是泛型方法
/// <summary>
/// 代码重用
/// </summary>
/// <param name="resource"></param>
/// <returns></returns>
public static List<T> JerryWhere<T>(this List<T> resource, Func<T, bool> func)
{
var list = new List<T>();
foreach (var item in resource)
{
if (func.Invoke(item)) // /* if (item.Age < 30)*///bool //item做为一个参数 返回一个bool
{
list.Add(item);
}
}
return list;
}
/// <summary>
/// 扩展方法:添加一个第三方静态类,把当前需要扩展的类作为参数添加方法,在第一个参数前加一个this
/// </summary>
/// <param name="student"></param>
public static void StudyPractise(this Student student)
{
Console.WriteLine("{0} {1}是匿名类中的黝!", student.Id, student.Name);
}
}