本文介绍了使用finally和函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有代码 private string GetName() { string name = ; 尝试 { name = 这是我的名字; // throw new NotImplementedException(); return 来自try; } catch (例外) { return 错误; } 最后 { name = ; // 清除对象内存。 } 返回名称; } 这个代码中的如果我想返回名字字符串我可以在结尾使用return该函数,但最终运行时,它清除名称值和函数返回空值。 如果我从尝试返回名称比其工作正常,但假设错误进来尝试像我写,然后尝试返回不执行和控制返回到底部,再次给我空白值。 所以,请建议哪种技术最好,为什么。解决方案 没有解决方案允许:始终使用finally块的返回值,只是因为它在try块的末尾执行 始终 其中发生了什么:捕获与否。 最简单的解决方案是在内部不设置 name finally块: 私人 string GetName() { string name = ; 尝试 { name = 这是我的名字; // throw new NotImplementedException(); } catch (例外) { name = 错误; } 最后 {} return 名称; } Hi,I have codeprivate string GetName() { string name = ""; try { name = "This is my name"; //throw new NotImplementedException(); return "from try"; } catch (Exception) { return "Error"; } finally { name = "";//clears object memory. } return name; }in this code if i want to return name string i can use return in the end of the function but when finally runs, it clears name value and function returns blank value.In case i return name from try than its working fine but suppose error comes in try like i write then this try return not executed and control goes to return at the bottom which gives me blank value again.So , please suggest which technique is best and why. 解决方案 There is no solution that allows that: the return value from the finally block will always be used, simply because it is always executed at the end of the try block regardless of what else happens within it: catch or not.The simplest solution is just to not set name within the finally block:private string GetName() { string name = ""; try { name = "This is my name"; //throw new NotImplementedException(); } catch (Exception) { name = "Error"; } finally { } return name; } 这篇关于使用finally和函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-20 10:35