基于Ardalis.GuardClauses守卫组件的拓展

在我们写程序的时候,经常会需要判断数据的是空值还是null值,基本上十个方法函数,八个要做这样的判断,因此我们很有必要拓展出来一个类来做监控,在这里我们使用一个简单地,可拓展的第三方组件:Ardalis.GuardClauses

在这里首先提一点,一般我们的一旦给一个实体类或者集合类初始化了之后,其值将不会是Null,示例:

List<Blog> Blogs = new List<Blog>(); 
或是 
Blog Blog = new Blog();

这两个变量都不是null,而是有地址的一个内存块了,但是由于我们没有赋值操作,其Count属性就是0了。

我们在Nuget中引入第三方组件Ardalis.GuardClauses。然后看看怎么使用,首先是最简单的string类型:

string SessionStr = HttpContext.Session.GetString("username"); 
Guard.Against.NullOrEmpty(SessionStr, nameof(SessionStr));

我们可以去看看这个组件的源码或者如何使用。这是最简单的。那么我们如果需要判断一个实体类型或者是集合类型应该怎么办?我们就自己拓展:
首先定义一个我们自己的异常类(当然你可以使用官方基于Exception类的拓展):

public class BlogExceptions : Exception 
{ 
 public BlogExceptions(string paramName) : base(string.Format("ParamName: {0} is null or empty", paramName)) 
 { 
 } 
 
 protected BlogExceptions(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) 
 { 
 } 
 
 public BlogExceptions(string message, Exception innerException) : base(message, innerException) 
 { 
 } 
}

关于Exception类的构造函数的使用,我们可以参考:
https://msdn.microsoft.com/zh-cn/library/system.exception.aspx
定义一个类GuardExtensions,但是这个类的命名空间最好要是Ardalis.GuardClauses,接下来基于既定的接口写拓展方法:

public static void NullOrEmptyBlog(this IGuardClause guardClause, List<Blog> blog, string paramName) 
{ 
 if(blog == null || blog.Count==0) 
 { 
 throw new BlogExceptions(paramName); 
 } 
}

最后调用就完事了:

List<Blog> Blogs = _context.Blogs.ToList(); 
Guard.Against.NullOrEmptyBlog(Blogs, nameof(Blogs));
posted @ 2018-07-14 14:11  又见阿郎  阅读(854)  评论(0编辑  收藏  举报