首先看用法: class Program
{
static void Main(string[] args)
{
string param = null;
try
{
DoSomething(param);
}
catch (ContractException ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
Console.ReadKey();
}
private static void DoSomething(string param)
{
Contract.Requires(x => param != null);
Console.WriteLine("after validating parameters..");
}
}
運行結果是:Exception: Contract broken: x => (value(CSharpByContract.Program+<>c__DisplayCla
ss0).param != null)
加粗的部分顯示了參數驗證失敗的原因.需要注意的是,我們在驗證時並不用手寫"param!=null"這樣的字串,節省了時間,也減少了不一致.
代碼: public static class Contract
{
/**//// <summary>
/// lazy programer's assert that gives a meaningful contract broken message
/// </summary>
/// <param name="condition">a bool expression to assert to be true</param>
public static void Requires(Expression<Func<object, bool>> condition)
{
var x = condition.Compile();
if (!x(null))
throw new ContractException(condition.ToString());
}
}
public class ContractException : ApplicationException
{
public ContractException(string message)
: base(string.Format("Contract broken: {0}", message))
{
}
}