使用扩展方法

 来自:http://www.dotnetbips.com/articles/dfeb8a51-4b3b-4bc6-aab9-28ac774b1e8c.aspx

比如想使用以下代码显示印度格式的时间(Indian Standard Time:IST):

 
  
DateTime dt = DateTime.Now;
DateTime utc
= dt.ToUniversalTime();
DateTime ist
= utc.AddMinutes( 330 );

使用下面2个扩展方法(注意:要用静态类、静态方法还参数中的this):

 
  
namespace Utils
{
public static class DateTimeHelper
{
public static DateTime ToIST( this DateTime dt)
{
DateTime utc
= dt.ToUniversalTime();
return utc.AddMinutes( 330 );
}

public static bool IsDate( this string s)
{
DateTime dt;
return DateTime.TryParse(s, out dt);
}
}
}

这样引用此命名空间后就可以使用扩展方法了:

TA_Ext_Methods_01.jpg2011050102013326.jpg

2011050102015620.jpg

注意:

  1. Extension methods can chain themselves. For example you may write something like this: dt.ToIST().ToDDMMYYYY()
    The ToIST() and ToDDMMYYYY() are assumed to be extension methods.
  2. Extension methods can be accessed only when its namespace is in scope
  3. If an extension method has the same signature as any of the instance method of the class it extends then the instance methods take precedence
  4. If two extension methods of a type have same signature them they must be called like normal static methods. For example, if you define two extension methods with same name and signature in two classes say DateTimeHelper1 and dateTimeHelper2, then they can be called  like this - DateTimeHelper1.ToIST(dt)

更多,更全的扩展方法文章:
http://www.cnblogs.com/ldp615/archive/2009/08/07/1541404.html

转载于:https://www.cnblogs.com/net205/archive/2011/05/01/2033705.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值