登录  /  注册

透过Parse和TryParse Try-Parse和Tester-Doer模式

黄舟
发布: 2017-03-04 10:36:38
原创
1305人浏览过

Parse和TryParse

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

            string dateTimeStr = "";
            DateTime dt = DateTime.Parse(dateTimeStr);
登录后复制

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

            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模式呢? 函数中写入异常,会降低性能,微软给出了这种模式来减小异常带来的副作用。
 
  如下代码:

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()分解为:

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模式是两种替代抛异常的优化方式,起到优化设计性能的作用。

 以上就是透过Parse和TryParse Try-Parse和Tester-Doer模式 的内容,更多相关内容请关注PHP中文网(www.php.cn)!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号