命名空间 : using System.Diagnostics.Contracts;
属性标记 : [ContractOption(category: "runtime", setting: "checking", enabled: true)]
事件订阅 : Contract.ContractFailed += (sender, e) => { Console.WriteLine(e.Message); };
1、 Requires() 定义前提条件
1 static void MinMax(int min,int max) 2 { 3 Contract.Requires(min <= max); 4 Contract.Requires <ArgumentException>(min <= max); 5 } 6 static void Preconditions(object o) 7 { 8 Contract.Requires<ArgumentNullException>(o != null, "Preconditions, o may not be null"); 9 Console.WriteLine(o.GetType().Name); 10 } 11 static void ArrayTest(int [] data) 12 { 13 Contract.Requires(Contract.ForAll(data, i => i < 12)); 14 Console.WriteLine("ArrayTest contract succeeded"); 15 } 16 public void ArrayTestWithPureMethod(int [] data) 17 { 18 Contract.Requires(Contract.ForAll(data, MyDataCheck)); 19 Console.WriteLine("ArrayWithPureMethod succeeded"); 20 } 21 22 public int MaxVal { get; set; } 23 public bool MyDataCheck(int x) 24 { 25 return x <= MaxVal; 26 }