高质量代码(一)
高质量代码(一)
一、Parse与TryParse
我们以Int32为例,首先看一下Int32提供的Parse和TryPase方法:
从Parse和TryParse方法上我们可以看出它们之间的主要区别在于:如果Prase转换失败则会直接抛出异常;而TryParse在转换失败的时候会返回false,并且将out的Int32值设置为0.
如果我们要使用Parse方法来处理任意字符串转换为Int32类型时,则要编写如下代码:
View Code
1 string str= ...;
2 Int32 value;
3 try
4 {
5 value = Int32.Parse(str);
6 }
7 catch (Exception)
8 {
9 value = 0 ;
10 }
代码量与TryParse相比多了许多,接下来我们来测试看两者之间的性能问题,代码如下:
View Code
1 Int32 count = 1000 ;
2 string strValue = " 123 " ;
3 Int32 intValue;
4
5 Stopwatch sw = Stopwatch.StartNew();
6 sw.Start();
7 for ( int i = 0 ; i < count; i++ )
8 {
9 Int32.Parse(strValue);
10 }
11 sw.Stop();
12 Console.WriteLine( " Int32.Parse(\"{0}\") => {1} " , strValue, sw.Elapsed);
13
14 sw.Restart();
15 sw.Start();
16 for ( int i = 0 ; i < count; i++ )
17 {
18 Int32.TryParse(strValue, out intValue);
19 }
20 sw.Stop();
21 Console.WriteLine( " Int32.TryParse(\"{0}\") => {1} " , strValue, sw.Elapsed);
22
23 strValue = " a123 " ;
24
25 sw.Restart();
26 sw.Start();
27 for ( int i = 0 ; i < count; i++ )
28 {
29 try
30 {
31 Int32.Parse(strValue);
32 }
33 catch (Exception) { }
34 }
35 sw.Stop();
36 Console.WriteLine( " Int32.Parse(\"{0}\") => {1} " , strValue, sw.Elapsed);
37
38 sw.Restart();
39 sw.Start();
40 for ( int i = 0 ; i < count; i++ )
41 {
42 Int32.TryParse(strValue, out intValue);
43 }
44 sw.Stop();
45 Console.WriteLine( " Int32.TryParse(\"{0}\") => {1} " , strValue, sw.Elapsed);
得出的结果:
二、枚举值
我们在编码当中经常会用到枚举,大多数情况下我们都是不会主动去给枚举添加任何默认值的,因为C#默认会给枚举赋值,然而当定义如下枚举时:
1 enum MyEnum
2 {
3 A = 1 ,
4 B = 2 ,
5 BC,
6 C = 3
7 }
此时的BC是什么值呢?首先编写测试代码来看看吧:
MyEnum myEnum = MyEnum.BC; Console.WriteLine(Convert.ToInt32(myEnum));
输出的结果竟然是: 3
于是又编写了如下测试代码:
MyEnum myEnum = MyEnum.BC;
Console.WriteLine( " {0} = {1} => {2} " , myEnum, MyEnum.C, myEnum == MyEnum.C);
返回竟然是: true
原因是编译器会给枚举元素逐个+1,当它发现BC并没有默认值的时候,编译器会在B的基础上+1并赋值给BC,因此BC=3,而枚举类型是值类型,因此有了以上的答案。
分类: C#
作者: Leo_wl
出处: http://HdhCmsTestcnblogs测试数据/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息