.NET卫队类库? [英] .NET Guard Class Library?

查看:119
本文介绍了.NET卫队类库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找一个库或源$ C ​​$ C,提供警卫的方法,如检查空参数。显然,这是相当容易建立,但我不知道是否有任何那里为.NET了。一个基本的谷歌搜索并没有透露太多。

I'm looking for a library or source code that provides guard methods such as checking for null arguments. Obviously this is rather simple to build, but I'm wondering if there are any out there for .NET already. A basic Google search didn't reveal much.

推荐答案

CuttingEdge.Conditions 。用法示例从页面:

public ICollection GetData(Nullable<int> id, string xml, ICollection col)
{
    // Check all preconditions:
    id.Requires("id")
        .IsNotNull()          // throws ArgumentNullException on failure
        .IsInRange(1, 999)    // ArgumentOutOfRangeException on failure
        .IsNotEqualTo(128);   // throws ArgumentException on failure

    xml.Requires("xml")
        .StartsWith("<data>") // throws ArgumentException on failure
        .EndsWith("</data>"); // throws ArgumentException on failure

    col.Requires("col")
        .IsNotNull()          // throws ArgumentNullException on failure
        .IsEmpty();           // throws ArgumentException on failure

    // Do some work

    // Example: Call a method that should not return null
    object result = BuildResults(xml, col);

    // Check all postconditions:
    result.Ensures("result")
        .IsOfType(typeof(ICollection)); // throws PostconditionException on failure

    return (ICollection)result;
}

另外一个不错的方法,它是不是打包在一个库中,但可以很容易地,的上Paint.Net博客

public static void Copy<T>(T[] dst, long dstOffset, T[] src, long srcOffset, long length)
{
    Validate.Begin()
            .IsNotNull(dst, "dst")
            .IsNotNull(src, "src")
            .Check()
            .IsPositive(length)
            .IsIndexInRange(dst, dstOffset, "dstOffset")
            .IsIndexInRange(dst, dstOffset + length, "dstOffset + length")
            .IsIndexInRange(src, srcOffset, "srcOffset")
            .IsIndexInRange(src, srcOffset + length, "srcOffset + length")
            .Check();

    for (int di = dstOffset; di < dstOffset + length; ++di)
        dst[di] = src[di - dstOffset + srcOffset];
}

我用它在我的项目,你可以从那里借了code

I use it in my project and you could borrow the code from there.

这篇关于.NET卫队类库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆