C#基础笔记之拓展方法
拓展方法:
概念:为现有的非静态/变量类型 添加方法
作用:
1、提升程序拓展性;
2、不需要再在对象中重新写方法;
3、不需要继承来添加方法;
4、为别人封装的类型写额外的方法;
特点:
1、静态类中的静态方法;
2、第一个参数(代表拓展的目标);
3、第一个参数前面一定要this;
注意:可以有返回值和n个参数;根据需求而定;
代码例子:
static class Speak { public static void SpeakInt(this int value) { Console.WriteLine(“卧槽,这个是为int拓展的方法” + value); } public static void SpeakString(this string str,string str1) { Console.WriteLine(“卧槽,这个是为string拓展的方法”+str); Console.WriteLine(“调用的对象”+str1); } } class Program { static void Main(string[] args){ int i=10; i.SpeakInt(); string str=”woc”; str.SpeakString(); } }