是否有一个使用属性的.NET参数验证标准框架?

oqui 发布于 2018-05-08 .net 最后更新 2018-05-08 17:17 207 浏览

有没有一个标准框架(可能是企业库或.NET本身的一部分),允许您在方法属性中执行常见的参数验证?

已邀请:

yvero

赞同来自:

ASP.NET(和ASP.NET MVC)的Dynamic Data允许您使用属性对模型属性进行验证。

qquas

赞同来自:

Microsoft企业库有Microsoft.Practices.EnterpriseLibrary.Validation库/名称空间,它允许使用属性进行验证。

funde

赞同来自:

您也可以使用postsharp并实现您自己的属性进行验证。

miure

赞同来自:

Microsoft Code Contracts是.NET Framework自4.0 CTP以来的一部分,可作为独立软件包用于较早版本的.NET Framework版本,允许指定编码假设。这包括指定可以验证参数的前提条件。 用于参数检查的示例应用程序(从Code Contracts documentation复制):

public Rational(int numerator, int denominator)
{
    Contract.Requires(denominator ! = 0);
this.numerator = numerator;
    this.denominator = denominator;
}
使用代码合同的好处是它是一个将成为未来.NET Framework版本的一部分的库,所以迟早你的应用程序中会少一个依赖项。 编辑:只是注意到,你特意要求一个图书馆,使用属性进行参数检查......代码合同不。代码合同不使用属性的原因列在其FAQ中:
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.

pdolor

赞同来自:

尽管微软代码合同出了一段时间,但它们仍然保存在MS Research中,并且您不能使用配置(app.config /数据库等)来打开/关闭甚至更改规则。我的库Bouncer提供了声明规则定义:源代码中的属性或实体类/属性级别的规则的app.config条目。该图书馆是LGPL下的开源软件(您可以在商业产品中免费使用它)。如果通过app.config配置规则,则可以在不需要重新编译的情况下调整规则设置。