来自: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);
}
}
}
这样引用此命名空间后就可以使用扩展方法了:
注意:
- 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. - Extension methods can be accessed only when its namespace is in scope
- 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
- 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