一、扩展方法是什么?
扩展方法必须是静态方法在静态类中,且至少有一个参数,该参数数据类型前需用this修饰,并且需要与调用者的数据类型一致。 使用时只需用参数的实例化对象.方法即可二、使用扩展方法的好处
使用扩展方法能够向现有对象添加方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型,并且是linq的重要组成部分Demo:
//Main方法
Console.WriteLine("****************************************");
string name = "小仙女";
//输出'小仙女mm'
Console.WriteLine(name.Test());
//输出'小仙女妹妹'
Console.WriteLine(name.Test1("妹妹"));
//数据源
List<Student> StudentList = new List<Student>()
{
new Student(){
Id=1,
Name="小仙女",
Age=18
},
new Student(){
Id=2,
Name="小仙女",
Age=20
},
new Student(){
Id=3,
Name="小仙女",
Age=21
},
new Student(){
Id=4,
Name="小仙女",
Age=22
}
};
//linq
var list1 = StudentList.GetStudents1(s => s.Age <= 20);
foreach (var item in list1)
{
Console.WriteLine($"ID: {item.Id},Name: {item.Name},Age: {item.Age}");
}
var list = StudentList.GetStudents();
foreach (var item in list)
{
Console.WriteLine($"ID: {item.Id},Name: {item.Name},Age: {item.Age}");
}
Console.WriteLine("****************************************");
Student student = new Student() { Age = 20, Id = 5, Name = "小仙女" };
Console.WriteLine(student.StudentTest());
*************************************************************************************
//静态类ExtendMethod
public static class ExtendMethod
{
/// <summary>
/// 返回符合查询的结果
/// </summary>
/// <param name="students">数据源</param>
/// <param name="func">委托</param>
/// <returns></returns>
public static List<Student> GetStudents1(this List<Student> students, Func<Student, bool> func)
{
var list = new List<Student>();
foreach (var item in students)
{
if (func.Invoke(item))
{
list.Add(item);
}
}
return list;
}
public static List<Student> GetStudents(this List<Student> students)
{
var list = new List<Student>();
foreach (var item in students.Where(s => s.Age <= 20))
{
list.Add(item);
}
return list;
}
public static bool StudentTest(this Student student)
{
if (student.Age >= 20)
return true;
return false;
}
public static string Test1(this string name, string cc)
{
return name + cc;
}
public static string Test(this string name)
{
return name + "mm";
}
}