题
我正在寻找提供保护方法的库或源代码,例如检查空参数。显然这个构建起来相当简单,但我想知道.NET是否还有。谷歌的基本搜索没有发现太多。
解决方案
有 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;
}
另一种不错的方法,它没有打包在库中,但很容易就是,:
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];
}
我在我的项目中使用它,您可以从那里借用代码。
其他提示
鉴于微软的代码合约随.NET 4.0推出,我试图找到一个主要是兼容,如果可能 - 如果不是,请自己写。这样,当您升级到.NET 4.0(最终)时,迁移将更容易。
您可以使用多种方法。
我最喜欢的是使用面向方面编程。查看PostSharp。
您还可以查看Spec#,C#的扩展名
在4.0中,您将拥有一个功能齐全的合同库。
最后,我的一位同事提出了一个非常有用的警卫库: http://blueonionsoftware.com/blog.aspx?p= ca49cb62-7ea2-43c5-96aa-91d11774fb48
我不知道任何商业上可用的。在模式<!>放大器中对这种类型的代码有一些支持;实践企业库。还有许多开源项目似乎也在不同程度上(在不同程度上)在CodePlex上执行此操作: http://www.codeplex.com/Project/ProjectDirectory.aspx?ProjectSearchText=validation 。
大多数情况下,这些类型的库最终都是自定义编写的,并且保留在使用它们的公司内部。
.NET 4.0中有支持使用 Code Contracts 提供相应的机制,基于Spec#。
我最近写了一篇关于警卫班的帖子(也没有发现任何信息): http://ajdotnet.wordpress.com/2009/08/01/posting-guards-guard-classes-explained/
我还发布了一个相应的Guard类实现(可以随意使用此代码,或根据您的需要调整它):ajdotnet.wordpress.com/guard-class /
关于Guard 4.0与.NET 4.0中的Code Contract(Spec#的后续版本)之间的关系,请查看以下帖子:www.leading-edge-dev.de/?p = 438
(抱歉碎片链接,网站只允许一个链接...)
HIH, AJ.NET
安装netfx-guard nuget包。你还得到了代码片段notnull和notempty,它的执行速度和你的手动检查一样快