日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

.NET框架-Try-Parse和Tester-Doer

發(fā)布時間:2023/12/20 asp.net 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 .NET框架-Try-Parse和Tester-Doer 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

作者:vuefine
文獻: msdn library
平臺:.NET 2.0+


Parse和TryParse

  DateTime中Parse(string s)和TryParse(string s, out datetime)都是用來將字符型的日期時間轉(zhuǎn)化為等效的System.DateTime。那么,他們之間有沒有區(qū)別呢,除了函數(shù)的參數(shù)不同外。先看下代碼:

string dateTimeStr = "";DateTime dt = DateTime.Parse(dateTimeStr);

  運行空字符串,將其轉(zhuǎn)化為日期時間型,顯然不能轉(zhuǎn)化,并且Parse()會拋出一個異常: System.FormatException: s 中不包含日期和時間的有效字符串表示形式。但是,運行TryParse這個轉(zhuǎn)化方法:

string dateTimeStr = ""; DateTime dt2; //dt2未經(jīng)初始化,就被傳遞給函數(shù)TryParse()bool sucflag = DateTime.TryParse(dateTimeStr, out dt2);

  轉(zhuǎn)化首先是不拋出異常的,dt2被賦值為日期時間的最小值,sucflag為false。看下對函數(shù)的注釋:

當此方法返回時,如果轉(zhuǎn)換成功,則包含與 s 中包含的日期和時間等效的 System.DateTime 值;如果轉(zhuǎn)換失敗,則為 System.DateTime.MinValue。如果s 參數(shù)為 null,是空字符串 (“”) 或者不包含日期和時間的有效字符串表示形式,則轉(zhuǎn)換失敗。*該參數(shù)未經(jīng)初始化即被傳遞。這個函數(shù)是不會拋出任何異常的。

Try-Parse

  看到他們的不同后,進一步來講,parse()拋出異常必然影響性能,TryParse()未拋出任何異常,這是一種優(yōu)化異常性能的設(shè)計模式,稱為Try-Parse Pattern。以下是微軟的官方解釋:

For extremely performance-sensitive APIs, an even faster pattern than the Tester-Doer Pattern described in the previous section should be used. The pattern calls for adjusting the member name to make a well-defined test case a part of the member semantics. For example, DateTime defines a Parse method that throws an exception if parsing of a string fails. It also defines a corresponding TryParse method that attempts to parse, but returns false if parsing is unsuccessful and returns the result of a successful parsing using an out parameter.

Tester-Doer

  在解釋Try-Parse模式時,微軟提出了另外一種模式:Tester-Doer模式,什么是Tester-Doer模式呢? 函數(shù)中寫入異常,會降低性能,微軟給出了這種模式來減小異常帶來的副作用。
 
  如下代碼:

ICollection<int> numbers = 省略獲取數(shù)據(jù)的邏輯 numbers.Add(1);//Add此處不做可寫性檢查

  以上缺陷:假如集合是只讀的,方法Add會拋出異常。調(diào)用這個方法的地方會經(jīng)常拋出異常,因此會影響系統(tǒng)的性能。為了避免這個設(shè)計缺陷,微軟提出: Sometimes performance of an exception-throwing member can be improved by breaking the member into two.

  將Add()分解為:

ICollection<int> numbers = 省略獲取數(shù)據(jù)的邏輯 if(!numbers.IsReadOnly) //Tester {numbers.Add(1); //Doer }

  Tester-Doer模式 總結(jié):

The member used to test a condition, which in our example is the property IsReadOnly, is referred to as the tester. The member used to perform a potentially throwing operation, the Add method in our example, is referred to as the doer.

   分解后,先做只讀性檢測,這樣會減少Add拋出只讀性異常的次數(shù),提升性能。

總結(jié)
  Try-Parse Pattern和Tester-Doer模式是兩種替代拋異常的優(yōu)化方式,起到優(yōu)化設(shè)計性能的作用。

總結(jié)

以上是生活随笔為你收集整理的.NET框架-Try-Parse和Tester-Doer的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。