.NET框架-Try-Parse和Tester-Doer的使用区别


本文摘自PHP中文网,作者黄舟,侵删。

Parse和TryParse

  DateTime中Parse(string s)和TryParse(string s, out datetime)都是用来将字符型的日期时间转化为等效的System.DateTime。那么,他们之间有没有区别呢,除了函数的参数不同外。先看下代码:

1

2

string dateTimeStr = "";

DateTime dt = DateTime.Parse(dateTimeStr);

  运行空字符串,将其转化为日期时间型,显然不能转化,并且Parse()会抛出一个异常: System.FormatException: s 中不包含日期和时间的有效字符串表示形式。但是,运行TryParse这个转化方法:

1

2

3

string dateTimeStr = "";      

DateTime dt2; //dt2未经初始化,就被传递给函数TryParse()

bool sucflag = DateTime.TryParse(dateTimeStr, out dt2);

  转化首先是不抛出异常的,dt2被赋值为日期时间的最小值,sucflag为false。看下对函数的注释:

当此方法返回时,如果转换成功,则包含与 s 中包含的日期和时间等效的 System.DateTime 值;如果转换失败,则为 System.DateTime.MinValue。如果s 参数为 null,是空字符串 (“”) 或者不包含日期和时间的有效字符串表示形式,则转换失败。*该参数未经初始化即被传递。这个函数是不会抛出任何异常的。

Try-Parse

  看到他们的不同后,进一步来讲,parse()抛出异常必然影响性能,TryParse()未抛出任何异常,这是一种优化异常性能的设计模式,称为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模式呢? 函数中写入异常,会降低性能,微软给出了这种模式来减小异常带来的副作用。
 
  如下代码:

1

2

ICollection<int> numbers = 省略获取数据的逻辑

numbers.Add(1);//Add此处不做可写性检查

  以上缺陷:假如集合是只读的,方法Add会抛出异常。调用这个方法的地方会经常抛出异常,因此会影响系统的性能。为了避免这个设计缺陷,微软提出: Sometimes performance of an exception-throwing member can be improved by breaking the member into two.

  将Add()分解为:

1

2

ICollection<int> numbers = 省略获取数据的逻辑if(!numbers.IsReadOnly) //Tester{

    numbers.Add(1); //Doer}

  Tester-Doer模式 总结:

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抛出只读性异常的次数,提升性能。

总结
  Try-Parse Pattern和Tester-Doer模式是两种替代抛异常的优化方式,起到优化设计性能的作用。

以上就是.NET框架-Try-Parse和Tester-Doer的使用区别的详细内容!

相关阅读 >>

.NET框架-集合相关所有类的思维导图分享

.NET框架-引用陷阱的代码实例分享

c#中.NET框架的简介

.NET框架-xml.serialization的思维导图分享

.NET框架-内存管理story与变量创建和销毁详解(图)

.NET框架-clone如何由浅变深的示例代码详解

.NET框架-异常设计原则详解

.NET框架-array的详细介绍

.NET框架-应用特性和反射检查数据唯一性的示例代码

.NET框架-string是value还是reference type的详解

更多相关阅读请进入《.NET框架》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...