扩展方法的重要性
面试当中会遇到,实际开发中也会用到。
扩展方法的作用
对于已经封装好的类,在不修改源码的基础上,为这个类添加一些新的方法。通俗的说,就是让本来没有这个方法的类有了这么一个方法,方便我们调用。
拓展方法的实现
1.使用场景
设想这样的场景:我们需要将string str="123"转换为int str=123(注:此处int为Int32类型)。按照面向对象的思路来看,应该使用str.ToInt32();对吧?但是我们发现C#源码中并未提供string类型的ToInt32()方法,我们也不能调用str.ToInt32()方法。
由于C#源码中并未提供str.ToInt32()方法,所以我们通常使用Convert.ToInt32(str);和int.Parse(str);来将string str="123"转为int str=123。
2.解决方法
此时有两个解决方法:
1.修改C#中string类的源代码;
2.不修改C#中string类的源代码,自己另外定义一个string类的拓展方法,来实现str.ToInt32()方法。
方法1是开发C#语言的人干的事情。对于我们这些C#语言的使用者,则使用方法2:自己定义一个string类的拓展方法,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//将string类型的"123"转换为int类型的123,并将123加上10之后输出
string str = "123";
Console.WriteLine(str.ToInt32(10));
Console.ReadKey();
}
}
public static class StringExtend
{
public static int ToInt32(this string str, int a)//拓展方法,对C#中string这个类进行拓展
{
return int.Parse(str) + a;
}
//public static void ToInt32(this string str)//拓展方法可以没有返回值
//{
// Console.WriteLine(int.Parse(str));
//}
}
}
运行截图如下:
3.实现了拓展方法ToInt32(),输入str就可以看到扩展方法ToInt32()了
4.扩展方法的语法
(1)新定义一个静态类。如这里定义为:StringExtend(注意:名字叫什么无所谓,但尽量让它有意义,如这里是对string这个类进行拓展,就取名为StringExtend)
(2)在静态类里面定义一个静态方法,即类名StringExtend和方法名ToInt32前都要加static。
(3)拓展方法有无返回值都可以。
(4)拓展方法的第一个参数前必须加this。(注:第一个参数指定该方法作用于哪个类型,如此处this string str指定我们拓展C#中的string类型)
注意:这里有一个易错的地方,即拓展方法不能放在普通的类中,例如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)//主函数
{
...
}
public static void ToInt32(this string str)//拓展方法的错误写法(不能放在class Program中)
{
...
}
}
}
而应该放在加了static的类中,例如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)//主函数
{
...
}
}
public static class StringExtend//类名叫什么无所谓,但尽量让它有意义,如这里是对string这个类进行拓展,就取名为StringExtend
{
public static void ToInt32(this string str)//拓展方法的正确写法
{
...
}
}
}
参考资料
黑马程序员
https://www.bilibili.com/video/BV1MW411n729?p=25