万金流
初次使用博客园,目前感觉还不错。 不知不觉用了4年零4个月了,越来越喜欢博客园。

对于已经写好的类,可以用扩展方法的形式在外面为它补充方法。

例(vs2013调试通过):

学生类

 1 class Student//普通类
 2     {
 3         private string name;
 4 
 5         public string Name
 6         {
 7             get { return name; }
 8             set { name = value; }
 9         }
10         private int age;
11 
12         public int Age
13         {
14             get { return age; }
15             set { age = value; }
16         }
17         
18     }

为其补充一个方法:

1 //可以为把所有的扩展方法全放在一个类中,这个类必须是静态的
2     static class Extends
3     {
4         //相应的,扩展方法也必须是静态的
5         public static void showMe(this Student xs,string msg)//this是关键字,为student类添加扩展方法
6         {
7             Console.WriteLine("Name:" + xs.Name + ",Age:" + xs.Age.ToString()+","+msg);
8         }
9     }

调用:

1 static void Main(string[] args)
2         {
3             Student a = new Student() { Name = "zs", Age = 20 };
4             a.showMe("haha");
5             Console.ReadKey();
6         }

运行结果:

posted on 2019-12-16 14:49  万金流  阅读(402)  评论(0编辑  收藏  举报