今天,咱们来聊一聊C#的扩展方法。app
C# 3.0中为咱们提供了一个新的特性—扩展方法。什么是扩展方法呢?咱们看一下MSDN的注解:this
扩展方法使您可以向现有类型“添加”方法,而无需建立新的派生类型、从新编译或以其余方式修改原始类型spa
也就是说,咱们能够为基础数据类型,如:String,Int,DataRow,DataTable等添加扩展方法,也能够为自定义类添加扩展方法。code
那么,咱们怎么向现有类型进行扩展呢?咱们再看看MSDN的定义:对象
扩展方法被定义为静态方法,但它们是经过实例方法语法进行调用的。 它们的第一个参数指定该方法做用于哪一个类型,而且该参数以 this 修饰符为前缀。blog
从定义能够看出,对现有类型进行扩展,需新建一个静态类,定义静态方法,方法的第一个参数用this指定类型。ip
下面,咱们看一下例子,首先,我定义一个静态类ObjectExtension,而后对全部对象都扩展一个ToNullString方法。若是对象为空,就返回string.Emptyci
不然,返回obj.ToString ()。get
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Reflection; namespace Amway.OA.MS.Common { public static class ObjectExtension { public static string ToNullString ( this object obj ) { if ( obj == null ) { return string.Empty; } return obj.ToString (); } } }
那么,咱们就能够在像如下那样进行调用:string
DateTime dt = DateTime.Now; var value = dt.ToNullString();
假如,咱们在进行转换过程当中,若是转成不成功,咱们返回一个默认值,能够编写以下代码:
public static int ToInt ( this object obj, int defaultValue ) { int i = defaultValue; if ( int.TryParse ( obj.ToNullString (), out i ) ) { return i; } else { return defaultValue; } } public static DateTime ToDateTime ( this object obj, DateTime defaultValue ) { DateTime i = defaultValue; if ( DateTime.TryParse ( obj.ToNullString (), out i ) ) { return i; } else { return defaultValue; } }
同理,对于自定义类,也能够进行方法扩展,以下,假如咱们新建类CITY
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AVON.DMS.Model { using System; using System.Collections.Generic; public partial class CITY { public decimal CITYID { get; set; } public Nullable<decimal> PROVINCEID { get; set; } public string ZIP { get; set; } } }
咱们在静态类中新建一个静态方法,以下:
public static string GetZip(this CITY city,string defaultvalue) { string value = defaultvalue; if (city != null) { return city.ZIP; } else return value; }
这样,每次新建类CITY时,就能够调用扩展方法GetZip获取当前类的ZIP值。
以上,是我对C#扩展类的理解,若有不正的地方,欢迎指正。谢谢。
今天写到这里,但愿对您有所帮助,O(∩_∩)O哈哈~