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形式 的内容,更多相关内容请关注ki4网(www.ki4.cn)!