扩展方法基本概念
为现有非静态的变量类型 添加新方法
作用
提升程序扩展性
不需要在对象中重新写方法
不需要继承来添加方法
为别人封装的类型写额外的方法
特点
写在静态类中
一定是个静态函数
第一个参数为扩展目标
第一个参数用this修饰
语法
访问修饰符 static 返回值 函数名(this 扩展类名 参数名 参数类型 参数名 参数类型)
cs
static class Tools{
public static void SpeakValue(this int value)
{
Console.WriteLine("为int扩展的方法"+value);
}
public static void SpeakStringInfo(this string str,string str2,string str3)
{
Console.WriteLine("为string扩展的方法");
Console.WriteLine("调用");
Console.WriteLine("传的参数"+str2 + str3);
}
public static void Fun2(this Test t)
{
Console.WriteLine("为Test的扩展方法");
}
}
public static void SpeakValue(this int value)
是为int扩展了一个成员方法
成员方法是需要实例化对象后才能使用的
value代表 使用该方法的实例化对象
使用逻辑
在任意一个静态类中写方法为系统自带的或者自己写的类型(非静态的变量类型)增加新方法
为自定义的类型扩展方法
cs
class Test
{
public int i = 10;
public void Fun1()
{
Console.WriteLine("123");
}
public void Fun2()
{
Console.WriteLine("44");
}
}
扩展方法的使用
cs
int i = 10;
i.SpeakValue();
string str = "000";
str.SpeakStringInfo("11", "22");
Test t = new Test();
t.Fun2();
如果扩展方法和原方法重合,那么调用的是原方法
扩展方法本质
扩展方法在编译后会被编译成普通的静态方法调用。
因此,扩展方法并不会真正改变类型本身,它只是一种语法糖,让代码更简洁、更具可读性。