擴充方法使用

來源:互聯網
上載者:User

上篇說道擴充方法的簡介,這裡就說繼續上篇說下用法。

擴充方法可以協助我們向現有類型中添加方法.來符合我們的需要。例如我們可以用擴充方法向string類中添加一個IsValidEmailAddress方法,用於檢測是否符合Email標準.


1定義擴充方法

擴充方法規定類必須是靜態.裡麵包含的所有方法必須都是靜態,(注意:不能定義擴充屬性和事件),且第一個參數指定方法作用的類型,用this修做首碼.

例如

public static classMyExtensions    {        public static int WordCount(this Stringstr)        {            return str.Split(new char[] { ' ','.', '?' },                            StringSplitOptions.RemoveEmptyEntries).Length;        }    }  

該方法的參數用this,表示自身修改的為this類型,

 

2使用

擴充方法被定義為靜態方法,但是通過執行個體才能調用,並且參數以this修改為首碼.而且是在編譯時間綁定的.在使用前首先引入命名空間,然後執行個體化對象就可以調用了。


3使用執行個體

String類的方法不少,但是有些用的不是很習慣.這裡寫了一個字元為空白的異常提示類.多用於傳遞查收的校正

首選定義靜態類.在定義靜態方法

using System;usingSystem.Collections.Generic;using System.Linq;using System.Web;usingSystem.Diagnostics;usingSystem.Reflection;using System.IO; namespace ConfigurationSectionTest1{ public  static class ThrowError{////DebuggerNonUserCode.如果設計器提供的類型和成員不是由使用者專門建立的代碼的一部分,則會增加調試過程的複雜性。 此特性禁止在調試器視窗中顯示這些附屬類型和成員,並自動逐句通過而不會進入並逐步執行設計器提供的代碼。 當逐句通過使用者代碼時,如果調試器遇到此特性,使用者將不會看到設計器提供的代碼,並且會執行使用者提供的下一條代碼語句。 ///<summary>/// 檢查對象是否為空白,如果為空白,拋出異常///</summary>///<typeparam name="T"></typeparam>///<param name="data"></param>///<param name="message"></param>///<param name="messageParams"></param>[DebuggerNonUserCode]publicstatic void NullCheck<T>(this object data, string message, paramsobject[] messageParams) where T : System.Exception  {    (data== null).TrueThrow<T>(message, messageParams);  } ///<summary>/// 檢查對象是否為空白,如果為空白,拋出ArgumentNullException///</summary>/// <param name="data">被檢查的對象</param>/// <paramname="message">參數的名稱</param>[DebuggerNonUserCode]publicstatic void NullCheck(this object data, string message) {   NullCheck<ArgumentNullException>(data,message); } ///<summary>/// 如果條件運算式boolExpression的結果值為真(true),則拋出strMessage指定的錯誤資訊///</summary>/// <paramname="parseExpressionResult">條件運算式</param>/// <paramname="message">錯誤資訊</param>/// <paramname="messageParams">錯誤資訊的參數</param>/// <typeparam name="T">異常的類型</typeparam>///<remarks>/// 如果條件運算式boolExpression的結果值為真(true),則拋出message指定的錯誤資訊[DebuggerNonUserCode]publicstatic void TrueThrow<T>(this bool parseExpressionResult, string message,params object[] messageParams) where T : System.Exception {   if(parseExpressionResult) {   if(message == null)   throw new ArgumentNullException("message");    Type exceptionType = typeof(T);   Objectobj = Activator.CreateInstance(exceptionType);    Type[]types = new Type[1];   types[0]= typeof(string);    ConstructorInfo constructorInfoObj = exceptionType.GetConstructor(   BindingFlags.Instance| BindingFlags.Public, null,   CallingConventions.HasThis,types, null);    Object[]args = new Object[1];    args[0]= string.Format(message, messageParams);    constructorInfoObj.Invoke(obj,args);    throw(Exception)obj;    }  } }}

對於調用法方,常用在方法的參數檢測上

Pubilc void test(string Id){ Id.NullCheck("字元Id不可為空");}
圖例

 執行個體化的Id可以直接調用該方法,進行判斷,為空白,則拋出我們寫好的提示。


 

小結:

以上是對string類型的擴充,當然了其他的類型也是可以擴充的,創造符合自己的需要的方法。由擴充方法聯想我們的靜態方法,靜態方式並不針對某一類型,但是擴充方法卻是這對某一類型的擴充,沒有繼承。這是他們的不同點。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.