码迷,mamicode.com
首页 > 其他好文 > 详细

try-catch-finally的含有return使用揭秘

时间:2015-08-27 15:11:37      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

 

很多人都会纠结这么一个问题try-catch-finally中有return的情况,我自己总结如下:

如果是值类型的话

请看代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace 含有return的测试
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             int j = Test();
13             Console.WriteLine(j);
14            
15         }
16         /// <summary>
17         /// 这个是测试return里面的是值类型就不会对他们有影响呢 
18         /// </summary>
19         /// <returns></returns>
20         static int Test()
21         {
22              int i = 0;
23 
24             try
25             {
26                
27                 return i; //为什么这里要加个return呢
28             }
29             catch (Exception)
30             {
31 
32                 i++;
33                 return i;
34 
35             }
36             finally
37             {
38                 i = i + 2;
39             }
40         
41         }
42         
43 
44     }
45 }

通过上面的代码可以看出,这里的finally执行了之后,对return返回没有影响 return返回结果还是0;
技术分享 

 

以下是返回值是引用类型

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace 引用类型测试
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             List<string> strList = Test();
13              foreach (var i in strList)
14             {
15                 Console.WriteLine(i);
16             }
17             Console.ReadKey();
18         }
19         private static List<string> Test()
20         {
21             List<string> strList = new List<string>();
22             strList.Add("aa");
23             strList.Add("bb");
24             strList.Add("cc");
25             try
26             {
27                 //这里没有发生异常的 
28                 strList.Add("trytry");
29                 return strList;
30             }
31             catch (Exception ex)
32             {
33                 strList.Add("zzz");
34                 return strList;
35             }
36             finally
37             {
38                 strList.Add("yyy");
39             }
40         }  
41 
42     }
43 }

输出结果如下:

技术分享

通过以上两个例子可以总结出来如果是值类型的话,finally里面的改变不会对try或者catch中的return返回值造成影响。

                                       如果是引用类型的话,finally里面的改变会对try或者catch中的return返回值造成影响。

至于为什么会出现这个结果: 我还在思考中,欢迎大家讨论

                         

 

 

 

try-catch-finally的含有return使用揭秘

标签:

原文地址:http://www.cnblogs.com/gdouzz/p/4763224.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!