本文导读:扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。 扩展方法当然不能破坏面向对象封装的概念,所以只能是访问所扩展类的public成员。
扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。
C#扩展方法第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。
声明扩展方法注:
1. 静态类 (扩展方法所在类是static)
2. 静态方法 (扩展方法是static)
3. 第一个参数(参数this和扩展的类型必不可少)
//必须是静态类才可以添加扩展方法
static class MyExtendHelper
{
//声明扩展方法注:
// 1. 静态类 (扩展方法所在类是static)
// 2. 静态方法 (扩展方法是static)
// 3. 第一个参数(参数this和扩展的类型必不可少)
//--------------------------
//-----示例1. 系统类扩展
//扩展方法必须是静态的,Add有三个参数
//this 必须有,string表示我要扩展的类型,stringName表示要扩展的类型参数名
// 扩展方法不带参数
public static string Add(this string stringName)
{
return stringName + "_a";
}
//扩展方法带1个参数
public static string Add(this string stringName,string addStr)
{
return stringName + addStr;
}
//-----示例2. 自定义类扩展
// 扩展方法不带参数
public static string ExtensionStuInfo(this Student stuName)
{
return stuName.StuInfo();
}
//扩展方法带参数2个参数
public static string ExtensionGetStuInfo(this Student student, string stuname, string stunum)
{
return student.getStuInfo(stuname, stunum) + "\\n读取完毕";
}
}
public class Student
{
public string StuInfo()
{
return "学生基本信息";
}
public string getStuInfo(string stuName, string stuNum)
{
return string.Format("学生信息:\\n" + "姓名:{0} \\n" + "学号:{1}", stuName, stuNum);
}
}
// 测试
public static void Main()
{
string str = "quzijing";
//注意调用扩展方法,必须用对象来调用
string Newstr = str.Add();
string Newstr2 = str.Add("_abc");
Console.WriteLine(Newstr);
Console.ReadKey();
Student newstudent = new Student();
//要使用对象调用我们的扩展方法
string stuinfo = newstudent.ExtensionStuInfo();
Console.WriteLine(stuinfo);
//要使用对象调用我们的扩展方法
string stuinformation = newstudent.ExtensionGetStuInfo("quzijing", "20081766");
Console.WriteLine(stuinformation);
Console.ReadKey();
}
this其他用法:
一 this代表当前类的实例对象
public class Test
{
private string scope = "全局变量";
public string getResult()
{
string scope = "局部变量";
// this代表Test的实例对象
// 所以this.scope对应的是全局变量
// scope对应的是getResult方法内的局部变量
return this.scope + "-" + scope;
}
}
二 用this串联构造函数
public class Test
{
public Test()
{
Console.WriteLine("无参构造函数");
}
// this()对应无参构造方法Test()
// 先执行Test(),后执行Test(string text)
public Test(string text) : this()
{
Console.WriteLine(text);
Console.WriteLine("有参构造函数");
}
}
三 为原始类型扩展方法
四 索引器(基于索引器封装EPList,用于优化大数据下频发的Linq查询引发的程序性能问题,通过索引从list集合中查询数据)
参照链接:https://www.cnblogs.com/opop/p/5553803.html
参照链接:https://www.cnblogs.com/yellowcool/p/7908607.html