您可能想查看Code Contracts。它们为您的方法提供静态和运行时检查,您也可以将它们应用到您的接口,以便合约成为您的公共 API 的一部分。
例如,从我自己的一些代码中复制而来(此代码在接口上实现合约):
using System;
using System.Diagnostics.Contracts;
using Project.Contracts.Model.Accounts;
using Project.Contracts.Services;
/// <summary>
/// Data access for accounts.
/// </summary>
[ContractClass(typeof(AccountRepositoryContract))]
public interface IAccountRepository
{
/// <summary>
/// Gets the user by id.
/// </summary>
/// <param name="userId">The user id.</param>
/// <returns>The user, or <c>null</c> if user not found.</returns>
[Pure]
User GetUserById(int userId);
}
/// <summary>
/// Contract class for <see cref="IAccountRepository"/>.
/// </summary>
[ContractClassFor(typeof(IAccountRepository))]
internal abstract class AccountRepositoryContract : IAccountRepository
{
/// <summary>
/// Gets the user by id.
/// </summary>
/// <param name="userId">The user id.</param>
/// <returns>
/// The user, or <c>null</c> if user not found.
/// </returns>
public User GetUserById(int userId)
{
Contract.Requires<ArgumentException>(userId > 0);
return null;
}
}
一个更简单但更全面的示例:
public class Foo
{
public String GetStuff(IThing thing)
{
// Throws ArgumentNullException if thing == null
Contract.Requires<ArgumentNullException>(thing != null);
// Static checking that this method never returns null
Contract.Ensures(Contract.Result<String>() != null);
return thing.ToString();
}
}