學(xué)習(xí)MVC時(shí),學(xué)會(huì)了寫擴(kuò)展方法,用起來很方便。
01 | using System; |
02 | using System.Collections.Generic; |
03 | using System.Linq; |
04 | using System.Web; |
05 | using System.Web.Mvc; |
06 | using System.Text; |
07 |
08 | namespace MvcApp1.Content |
09 | { |
10 |
//<%@ Import Namespace="MvcApp1.Content" %> |
11 |
public static class MyHtmlHelper |
12 |
{ |
13 |
public static string RedLable( this HtmlHelper helper, string lbstr) |
14 |
{ |
15 |
StringBuilder sb = new StringBuilder(); |
16 |
sb.Append( "<span style=" color:red; ">" ); |
17 |
sb.Append(lbstr); |
18 |
sb.Append( "</span>" ); |
19 |
return sb.ToString(); |
20 |
} |
21 |
} |
22 | } |
下面,用上面這個(gè)形式來寫我的擴(kuò)展方法
001 | using System; |
002 | using System.Collections.Generic; |
003 | using System.Text; |
004 |
005 | namespace Tools.Common |
006 | { |
007 |
/// <summary> /// 數(shù)據(jù)優(yōu)化公共類 |
008 |
/// </summary> public static class DataHelper |
009 |
{ |
010 |
#region 根據(jù)是否為null或""返回string類型數(shù)據(jù) |
011 |
/// <summary> /// 根據(jù)是否為null或""返回string類型數(shù)據(jù) |
012 |
/// </summary> /// <param name="obj">要獲取數(shù)據(jù)的對象 |
013 |
/// <param name="defaultValue">為null或""時(shí)返回的默認(rèn)值,不指定則返回"" |
014 |
/// <returns></returns> public static string IsNull(this object obj, params object[] defaultValue) |
015 |
{ |
016 |
if (obj == null || "" .Equals(obj.ToString().Trim())) |
017 |
{ |
018 |
if (defaultValue.Length == 0 || defaultValue[0]== null ) return "" ; |