如何在If/Else语句外部使用其内部定义的字符串变量?
解决If/Else赋值变量后外部访问报错的问题
你的需求完全可行,报错原因是变量作用域问题:你在if和else的代码块内部分别声明了string bell,这两个变量的作用域只限于各自的代码块,出了代码块就无法访问,所以外部的finalMessage无法识别bell变量。
替代方案1:提前在外部声明变量(最直观的解决方式)
在if/else代码块之外先声明bell变量,然后在内部给它赋值:
bool hitBell = bellCounter == 0; string bell; // 先在外部声明变量,扩大作用域 if (hitBell) { bell = "You just hit the bell for the first time."; } else { bell = $"You just hit the bell. But, you already rang it {bellCounter} times before, you are such an impatient person"; } string finalMessage = $"{bell}, let's hope the auditor reacts to it."; // 后续递增bellCounter的代码
替代方案2:使用三元运算符简化代码
如果只是二分支的赋值逻辑,可以用三元运算符一行搞定,代码更简洁:
bool hitBell = bellCounter == 0; string bell = hitBell ? "You just hit the bell for the first time." : $"You just hit the bell. But, you already rang it {bellCounter} times before, you are such an impatient person"; string finalMessage = $"{bell}, let's hope the auditor reacts to it."; // 后续递增bellCounter的代码
内容的提问来源于stack exchange,提问作者StefanBraun
相关产品推荐
相关产品推荐

