.NET Guard类库?

Bri*_*nga 16 .net code-contracts

我正在寻找提供保护方法的库或源代码,例如检查空参数.显然这个构建起来相当简单,但我想知道.NET是否还有.谷歌的基本搜索没有透露太多信息.

Ale*_*nov 12

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;
}
Run Code Online (Sandbox Code Playgroud)

另一个很好的方法,不是打包在库中,但可以很容易地在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];
}
Run Code Online (Sandbox Code Playgroud)

我在我的项目中使用它,你可以从那里借用代码.


Jon*_*eet 8

考虑到微软的代码合约与.NET 4.0一起发布,我试图找到一个大部分兼容的,如果可能的话 - 如果没有,请自己编写.这样,当您升级到.NET 4.0(最终)时,迁移将更容易.