C#扩展方法

扩展方法的目的就是为一个现有类型添加一个方法,现有类型既可以是int,string等数据类型,也可以是自定义的数据类型。

为数据类型的添加一个方法的理解:一般来说,int数据类型有个Tostring的方法,就是把int 数据转换为字符串的类型,比如现在我们想在转换成字符串的时候还添加一点东西,比如增加一个字符 a .那么之前的Tostring就不好使了,因为它只是它我们的int数据转换为string类型的,却并不能添加一个字母 a.所以这就要用到所谓的扩展方法了。

首先我们看一个给现有的类型增加一个扩展方法。

我们想给string 类型增加一个Add方法,该方法的作用是给字符串增加一个字母a.

 1 //必须是静态类才可以添加扩展方法
 2 Static class Program
 3        {
 4         static void Main(string[] args)
 5         {
 6             string str = "quzijing";
 7 //注意调用扩展方法,必须用对象来调用 
 8             string Newstr = str.Add();
 9             Console.WriteLine(Newstr);
10             Console.ReadKey();
11         }
12 //声明扩展方法
13         //扩展方法必须是静态的,Add有三个参数
14         //this 必须有,string表示我要扩展的类型,stringName表示对象名
15         //三个参数this和扩展的类型必不可少,对象名可以自己随意取如果需要传递参数,//再增加一个变量即可
16 
17         public static  string  Add(this string stringName)
18         {
19             return stringName+"a";
20         }
21 }
View Code

我们再来尝试给我们自定义的类型增加一个扩展方法,并增加一个传递的参数。

首先我们声明一个Student类,它包含了两个方法StuInfo,getStuInfo.实例代码如下:

 1 public class Student
 2     {
 3         public string StuInfo()
 4         {
 5             return "学生基本信息";
 6         }
 7         public  string getStuInfo(string stuName, string stuNum)
 8         {
 9        return string.Format("学生信息:
" + "姓名:{0} 
" + "学号:{1}", stuName, stuNum);
10         }
11      }
View Code

之后我们再声明一个名为ExtensionStudentInfo的静态类,注意必须为静态

这个类的作用就是包含一些我们想要扩展的方法,在此我们声明两个Student类型的扩展方法,Student类型为我们自定义的类型。示例代码如下:

 1 public static class ExtensionStudentInfo
 2     {
 3         //声明扩展方法
 4         //要扩展的方法必须是静态的方法,Add有三个参数
 5         //this 必须有,string表示我要扩展的类型,stringName表示对象名
 6         //三个参数this和扩展的类型必不可少,对象名可以自己随意取如果需要传递参数,再增加一个变量即可
 7         public static string ExtensionStuInfo(this Student stuName)
 8         {
 9             return stuName.StuInfo();
10         }
11         //声明扩展方法
12         //要扩展的方法必须是静态的方法,Add有三个参数
13         //this 必须有,string表示我要扩展的类型,stringName表示对象名
14         //三个参数this和扩展的类型必不可少,对象名可以自己随意取如果需要传递参数,在此我们增加了两个string类型的参数
15         public static string ExtensionGetStuInfo(this Student student, string stuname, string stunum)
16         {
17             return student.getStuInfo(stuname, stunum)+"
读取完毕";
18         }
19     }
View Code

以上的工作做完之后便可以使用我们的扩展方法了,注意必须要用对象来调用扩展方法。

 1 static void Main(string[] args)
 2         {
 3             Student newstudent = new Student();
 4 //要使用对象调用我们的扩展方法
 5             string stuinfo = newstudent.ExtensionStuInfo();
 6             Console.WriteLine(stuinfo);
 7 //要使用对象调用我们的扩展方法
 8 string stuinformation = newstudent.ExtensionGetStuInfo("quzijing", "20081766");
 9             Console.WriteLine(stuinformation);
10             Console.ReadKey();
11         }
View Code
原文地址:https://www.cnblogs.com/farmer-y/p/5938947.html