有没有任何原因不使用代码合同来强制执行业务规则?
想象一下你有一个代表系统中单个用户并定义可以针对其他用户执行的操作的类。您可以编写像这样的ChangePassword
方法...
public void ChangePassword(User requestingUser, string newPassword)
{
Contract.Requires<ArgumentNullException>(requestingUser);
Contract.Requires<ArgumentNullException>(newPassword);
// Users can always change their own password, but they must be an
// administrator to change someone else's.
if (requestingUser.UserId != this.UserId &&
!requestingUser.IsInRole("Administrator"))
throw new SecurityException("You don't have permission to do that.");
// Change the password.
...
}
或者你可以使用Contract.Requires
将安全检查作为先决条件实现...
public void ChangePassword(User requestingUser, string newPassword)
{
Contract.Requires<ArgumentNullException>(requestingUser != null);
Contract.Requires<ArgumentNullException>(newPassword != null);
// Users can always change their own password, but they must be an
// administrator to change someone else's.
Contract.Requires<SecurityException>(
requestingUser.UserId == this.UserId ||
!requestingUser.IsInRole("Administrator"),
"You don't have permission to do that.");
// Change the password.
...
}
这两种方法有哪些优缺点呢?
ContractException
是无法捕获的,但是你的回答指引了我正确的方向:http://www.infoq.com/articles/code-contracts-csharp - 谢谢! :) - Richard Poole