2008-11-18 71 views
14

我正在寻找一个库或源代码,它提供了诸如检查空参数之类的守护方法。很明显,这是相当简单的构建,但我想知道是否有任何.NET的。基本的谷歌搜索没有透露太多。.NET Guard类库?

回答

11

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; 
} 

另外一个不错的方法,这是不是在一个库包装,但可以很容易地,on Paint.Net blog

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]; 
} 

我用它在my project,你可以借代码从那里。

+0

我将此标记为公认的答案,因为它确实符合我的需求。 – 2011-04-21 03:42:00

8

鉴于微软的Code Contracts与.NET 4.0问世,如果可能的话,我会尽量找到一个兼容的,如果没有的话,自己写。当你升级到.NET 4.0时(最终),迁移将变得更加容易。

1

我最近写了一篇关于警卫班后(已没有发现任何信息其一):http://ajdotnet.wordpress.com/2009/08/01/posting-guards-guard-classes-explained/

我还出版了各保护类的实现(随意直接使用这些代码,或将其调整到您的需求):ajdotnet.wordpress.com/guard-class/

关于.NET 4.0中Guard类和代码契约之间的关系(Spec#的后继者),请看下面的帖子:www.leading -edge-dev.de/?p=438

(遗憾的是分段链接,网站只允许一个链接...)

HIH, AJ.NET

0

安装netfx-guard nuget包。您还会得到代码片段notnull和notempty,它的执行速度与您的手动检查一样快。