Posts
.NET 4.0 New Feature - 程式碼合約(Code Contracts) (三) Contract.Assert Contract.Assume
public static int CalculateSomeValues() { Contract.Ensures(Contract.Result<int>() > 0); return 1; }</pre></div> <p> </p> <p>由於在CalculateSomeValues函式內,已經用後置條件去驗證了函式回傳值,因此在Main裡面的Contract.Assert就可以確定x變數一定會滿足驗證條件,故整個程式在做靜態分析時是會通過驗證的。</p> <p> </p> <p>而若今天我們的函式並未用後置條件去確保有正確的函式回傳值的話,這樣的程式在Contract.Assert那段就會被檢查出有問題。因為回傳值不確定,這個Assert在靜態分析中就無法被驗證,也就無法確定x變數一定會大於零。 </p> <p><img style="border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px" border="0" alt="image" width="398" height="244" src="\images\posts\17802\image_thumb_2.png" /></a> </p> <p><a href="http://files.dotblogs.com.tw/larrynung/1009/.NET4.0NewFeatureCodeContracts_B520/image_4.png"><img style="border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px" border="0" alt="image" width="447" height="129" src="\images\posts\17802\image_thumb_1.png" /></a></p> <p> </p> <p>這時若仍不想為函式加入後置方法,讓整個驗證更為嚴謹的話,可以使用Contract.Assume來做驗證的動作。</p> <p><a href="http://files.dotblogs.com.tw/larrynung/1009/.NET4.0NewFeatureCodeContracts_B520/image_8.png"><img style="border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px" border="0" alt="image" width="404" height="247" src="\images\posts\17802\image_thumb_3.png" /></a></p> <p><a href="http://files.
read morePosts
.NET 4.0 New Feature - 程式碼合約(Code Contracts) (二) 三大合約
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(MyProperty >= 0); }
public int MyProperty { get; set; }
[ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(MyProperty >= 0); } 這邊我們來反組譯了解一下其運作原理,反組譯後可發現Code Contract偷偷的幫我們在裡面造了兩個私有欄位<MyProperty>k_backingField與$evaluatingInvariant$。 <img alt="" src="\images\posts\17516
read morePosts
[.NET Concept]使用BeginXXX/EndXXX與SuspendLayout/ResumeLayout時,考慮加上Try/Finally
Private Sub Application_ThreadException(ByVal sender As Object, ByVal e As EventArgs) ... End Sub</pre></div>
read morePosts
[.Net Concept]適時採用事件動態繫結來替代用If判斷作功能的啟用
Private _enableLogData As Boolean Public Property EnableLogData() As Boolean Get Return _enableLogData End Get Set(ByVal value As Boolean) _enableLogData = value End Set End Property Event Executing As EventHandler Event Executed As EventHandler Protected Sub OnExecuting(ByVal e As EventArgs) RaiseEvent Executing(Me, e) End Sub Protected Sub OnExecuted(ByVal e As EventArgs) RaiseEvent Executed(Me, e) End Sub Sub GoExecute() For i As Integer = 1 To 100000000 OnExecuting(New EventArgs) '運行動作,這邊為了看出差異,故不做動作 If EnableLogData Then '紀錄動作,這邊為了看出差異,故不做動作 End If OnExecuted(New EventArgs) Next End Sub End Class
read more