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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,789评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,127评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,805评论 18 399
  • <?php /** * 常用函数库 * */ class Core_Fun { /** * 对变量进行反...
    寻梦xunm阅读 534评论 0 0
  • 从我记事起,我就浸泡在音乐里。可能别人家只有收音机的时候,我家已经有了录音机,接着有了老爸亲手做的高低音齐全的大音...
    艺菲_夏阅读 262评论 3 4