是否存在用于使用属性的.NET参数验证的标准框架?

时间:2020-03-06 14:46:12  来源:igfitidea点击:

是否有一个标准框架(可能是Enterprise Library ...或者.NET本身的一部分)允许我们在方法属性中进行通用参数验证?

解决方案

ASP.NET(和ASP.NET MVC)的动态数据使我们可以使用属性对模型属性进行验证。

Microsoft Enterprise Library具有Microsoft.Practices.EnterpriseLibrary.Validation库/命名空间,该库/命名空间允许使用属性进行验证。

我们也可以使用postharp并实现自己的属性以进行验证。

Microsoft代码协定自4.0 CTP开始是.NET Framework的一部分,并且作为独立软件包可用于.NET Framework的早期版本,允许指定编码假设。这包括指定可以验证参数的前提条件。

参数检查的一个示例用法是(从代码合同文档中复制):

public Rational(int numerator, int denominator)
{
    Contract.Requires(denominator ! = 0);

    this.numerator = numerator;
    this.denominator = denominator;
}

使用代码协定的好处是它是一个库,它将成为将来.NET Framework版本的一部分,因此,迟早我们在应用程序中的依赖性将减少。

编辑:刚注意到我们专门要求使用属性进行参数检查的库...该代码合同不。常见问题列出了代码合同不使用属性的原因:

The advantage of using custom attributes is that they do not impact the code at all. However, the benefits of using method calls far outweigh the seemingly natural first choice of attributes:
  
  Runtime support: Without depending on a binary rewriter, contracts expressed with attributes cannot be enforced at runtime. This means that if there are preconditions (or other contracts) that you want enforced at runtime, you need to either duplicate the contracts in the code or else include a binary rewriter in your build process. Contract.RequiresAlways serves both as a declarative contract and as a runtime-checked validation.
  
  Need for parsing: Since the values that can be used with custom attributes are limited, conditions end up being encoded as strings. This requires defining a new language that is appropriate for all source languages, requires the strings to be parsed, duplicating all of the functionality the compiler already possesses.
  
  Lack of IDE support: Expressed as strings, there is no support for Intellisense, type checking, or refactoring, all of which are available for authoring contracts as code.

这是使用PostSharp的示例
http://dpatrickcaldwell.blogspot.com/2009/03/validate-parameters-using-attributes.html

尽管Microsoft Code Contracts已有一段时间,但它们仍托管在MS Research中,并且我们不能使用配置(app.config /数据库等)来打开/关闭甚至更改规则。我的库Bouncer确实提供了声明性的规则定义:源代码或者app.config条目中的属性,用于实体类/属性级别的规则。该库在LGPL下是开源的(我们可以在商业产品中自由使用它)。如果通过app.config配置规则,则无需重新编译即可调整规则设置。