來看看兩種好玩的方法,擴展方法和分部方法

  很久沒過來扯淡了,話說這年頭還有偶遇的事情嗎?好比國慶回家的汽車上有個妹子要你qq,要你微信,想着法子跟你聊天,而後睡了一覺,醒來發現微信

腎不見了?小花絮小花絮,要是腎真沒了,也吹不了牛,敗不了火了,繼續言歸正傳。app

 

一:擴展方法函數

       說到擴展方法,我想你們都已經再熟悉不過了,也許你的解決方案中有無數個這樣的擴展方法,自從有了Linq以後,咱們的集合就不再單純了。this

從下面的Linq類中,全部的方法都擴展在IEnumerable<T>上,偏偏咱們的集合都繼承於IEnumerable接口下面。編碼

 

而後咱們在編碼的時候就來了不少這樣的擴展方法。spa

 

 

那麼如今問題來了,學挖掘機技術哪家強o(∩_∩)o...?3d

 

下面舉一個擴展string類的一個Asint()方法,而後看看IL代碼都幹了些什麼?版本控制

 1 namespace ConsoleApplication1
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             var s = "123".AsInt();
 8         }
 9     }
10 
11     public static class StringExtension
12     {
13         public static int AsInt(this string value, int defaultValue = 0)
14         {
15             int result;
16             if (!int.TryParse(value, out result))
17             {
18                 return defaultValue;
19             }
20             return result;
21         }
22     }
23 }

 

IL代碼:日誌

 

從IL的call指令能夠看出,其實擴展方法本質上是調用靜態類StringExtension中的AsInt方法,因此能夠看出其實這也是編譯器爲了提升咱們的開發code

效率而提供的的一個語法糖而已,因此上面的寫法一樣能夠寫成這樣,一樣能夠看出下面的寫法就麻煩了不少。

1            s = StringExtension.AsInt("123");

 

那麼下面又來了一個問題,既然能夠隨意擴展,那麼我能不能擴展string類的任何一個方法?好比說ToLower()? 從下圖中咱們能夠獲得答案,在vs的智能感

知中顯示出的方法仍是string自帶的方法,而不是我擴展的方法,這就說明編譯器在用方法的時候仍是有優先級的,正是由於有了這個優先級的問題,給咱們

帶來了一個很大的「版本控制問題」,就好比我剛纔擴展的Asint()方法,若是後期的CLR版本中在String類中本身增長了Asint()方法的話,那我擴展的Asint()

方法今後就會被忘卻於天涯,因此這個問題要留一點心。

 

二:分部方法

   提及分部方法,你可能會問它有什麼應用場景,畢竟在咱們實際的編碼中不多使用到,到是分部類用的很多,因此啦,我必須找點場景出來。

剛好在EF中還真給找到了。

     具體怎麼建一個EF文件就不說啦,咱們就看看EF生成的模板代碼。

 1 public partial class DataClasses1DataContext : System.Data.Linq.DataContext
 2     {
 3         
 4         private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
 5         
 6     #region 可擴展性方法定義
 7     partial void OnCreated();
 8     #endregion
 9         
10         public DataClasses1DataContext() : 
11                 base(global::System.Configuration.ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString, mappingSource)
12         {
13             OnCreated();
14         }
15         
16         public DataClasses1DataContext(string connection) : 
17                 base(connection, mappingSource)
18         {
19             OnCreated();
20         }
21         
22         public DataClasses1DataContext(System.Data.IDbConnection connection) : 
23                 base(connection, mappingSource)
24         {
25             OnCreated();
26         }
27         
28         public DataClasses1DataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
29                 base(connection, mappingSource)
30         {
31             OnCreated();
32         }
33         
34         public DataClasses1DataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
35                 base(connection, mappingSource)
36         {
37             OnCreated();
38         }
39         
40         public System.Data.Linq.Table<Student> Student
41         {
42             get
43             {
44                 return this.GetTable<Student>();
45             }
46         }
47     }

能夠看到在幾乎全部的構造函數中都有這樣的一個OnCreated方法,這個具體的OnCreated的實現,你能夠自定義一個分部方法來實現。裏面能夠放些你認

爲適應你項目須要的東西,好比:日誌,統計啥的。

 

根據上面EF的例子,我舉個簡簡單單的sample,就是用Log方法來記錄當前登錄該DB的用戶

 1 namespace ConsoleApplication1
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             for (int i = 0; i < 10; i++)
 8             {
 9                 var db = new DB();
10             }
11 
12             Console.Read();
13         }
14     }
15 
16     /// <summary>
17     /// 好比這是codesmith生成的代碼
18     /// </summary>
19     public partial class DB
20     {
21         partial void Log();
22 
23         public DB()
24         {
25             Log();
26         }
27     }
28 
29     /// <summary>
30     /// 本身實現的代碼
31     /// </summary>
32     public partial class DB
33     {
34         public static int instanceCount = 0;
35 
36         partial void Log()
37         {
38             Console.WriteLine("當前是第{0}個用戶登錄DB", ++instanceCount);
39         }
40 
41         ~DB()
42         {
43             instanceCount--;
44         }
45 
46     }
47 }

 

再來看看IL:

 

 

能夠看出在編譯器編譯以後,自動生成的DB和我自定義的DB類已經合二爲一了,固然這必須是咱們預期的結果,不過這裏有一個小注意的地方,若是這

裏我沒有實現自定義的Log方法,那麼自動生成DB類中的Log方法會何去何從呢?由於它僅僅是定義一個方法的口子,並無實現。

 1 namespace ConsoleApplication1
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             for (int i = 0; i < 10; i++)
 8             {
 9                 var db = new DB();
10             }
11 
12             Console.Read();
13         }
14     }
15 
16     /// <summary>
17     /// 好比這是codesmith生成的代碼
18     /// </summary>
19     public partial class DB
20     {
21         partial void Log();
22 
23         public DB()
24         {
25             Log();
26         }
27     }
28 }

 

從上面的圖中能夠看到兩點好玩的地方:

①: 已經沒有了Log方法的IL指令,這就說明若是隻定義了方法接口而不實現的話,編譯器會直接忽視它。

②: 根據上一條的意思,咱們也不難理解爲何在ctor上沒有了log方法,而僅僅是默認調用父類的構造函數,因此編譯器真的很智能。

相關文章
相關標籤/搜索