您的位置:首页 > 编程语言 > C#

C# 3.0 特性之扩展方法

2015-07-26 20:51 507 查看
今天,我们来聊一聊C#的扩展方法。

C# 3.0中为我们提供了一个新的特性—扩展方法。什么是扩展方法呢?我们看一下MSDN的注解:

扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型

也就是说,我们可以为基础数据类型,如:String,Int,DataRow,DataTable等添加扩展方法,也可以为自定义类添加扩展方法。

那么,我们怎么向现有类型进行扩展呢?我们再看看MSDN的定义:

扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。

从定义可以看出,对现有类型进行扩展,需新建一个静态类,定义静态方法,方法的第一个参数用this指定类型。

下面,我们看一下例子,首先,我定义一个静态类ObjectExtension,然后对所有对象都扩展一个ToNullString方法。如果对象为空,就返回string.Empty

否则,返回obj.ToString ()。

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 ();
}
}
}


那么,我们就可以在像以下那样进行调用:

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哈哈~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: