c#编程小细节

来源: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且不为空的时候

if ( str == null || str == "" ){}

if ( array == null || array.Length == 0 ){}

if ( list == null || list.Count == 0 ){}

如果觉得上面那样写太麻烦了,可以写一个像下面那样写一个静态类,调里面的静态函数

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

你可能感兴趣的:(c#编程小细节)