C#_扩展方法

//当一个类不能再修改时,需要添加其他额外的方法---》扩展方法

步骤:1.创建一个静态类  保证该类与要扩展的类在同一个命名空间下

   2.在静态类中创建静态方法  标记静态方法的参数  (this 类型 ob)  this 必不可少  类型为要扩展的类型  ob为将来要引用该扩展方法的对象

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _13扩展方法练习
 8 {
 9     /// <summary>
10     /// Date:2015-11-26
11     /// Author:Xuqingchi
12     /// Version:vs2012
13     /// </summary>
14     class Program
15     {
16         static void Main(string[] args)
17         {
18 
19             //第一步: 创建静态类  
20             //第二步: 创建静态方法(this TestClass ob)
21             TestClass tc1=new TestClass(){Id="Xuqingchi"};
22             tc1.DoSth();
23 
24             //调用扩展方法
25             tc1.DoSthElse();
26 
27         }
28     }
29 
30      public class TestClass
31     {
32 
33         private string _id;
34 
35         public string Id
36         {
37           get { return _id; }
38           set { _id = value; }
39         }
40 
41          public  void DoSth()
42          {
43              Console.WriteLine("testClass do sth...");
44          }
45 
46     }
47 }
调用扩展方法
namespace _13扩展方法练习
{
    static class Class1
    {
        //该静态方法的第一个参数  this 是必须得 扩展的对象  obj就表示将来要调用此方法的对象 
        public static void DoSthElse(this TestClass o)
        {
            Console.WriteLine("Do Sth else .^_~ .   {0}",o.Id);
        }
    }
}
创建的静态类

 

posted on 2015-11-26 20:47  许清池  阅读(135)  评论(0编辑  收藏  举报

导航