來源:https://qiita.com/baba_s/items/f2ad850dd7fc84165e96
1.避免null值
《1》變量初始化
private string str = string.Empty;
private List list = new List();
private Dictionary dict = new Dictionary();
private Action act = delegate{};
《2》判斷不為null且不為空的時(shí)候
if ( str == null || str == "" ){}
if ( array == null || array.Length == 0 ){}
if ( list == null || list.Count == 0 ){}
如果覺得上面那樣寫太麻煩了饭豹,可以寫一個(gè)像下面那樣寫一個(gè)靜態(tài)類抖拴,調(diào)里面的靜態(tài)函數(shù)
public static class StringExtensions{
public static bool IsNullOrEmpty( this string self ){
return string.IsNullOrEmpty( self );}
public static bool IsNullOrWhiteSpace( this string self ){
return self == null || self.Trim() == "";}
public static bool IsNullOrEmpty( this IList self ){
return self == null || self.Count == 0;}}
寫完后,就變成了
if ( str.IsNullOrEmpty() ){}
if ( str.IsNullOrWhiteSpace() ){}
if ( array.IsNullOrEmpty() ){}
if ( list.IsNullOrEmpty() ){}