我想知道为什么我需要在下面的代码中将返回语法放两次,
public string test(){
bool a = true;
if(a){
string result = "A is true";
}else{
string result = "A is not true";
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
它会出现一个错误,表示当前上下文中不存在名称"result".
但不管怎样,都有结果变量.嗯..
所以我改变了这样的代码,
public string test(){
bool a = true;
if(a){
string result = "A is true";
return result;
}else{
string result = "A is not true";
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
然后它工作.这样使用是否正确?
请告诉我,
谢谢!
你只是错过了result代码块中的声明..我个人无论如何都会建议第二个代码块(更正时)但是这里......
public string test(){
bool a = true;
string result = string.Empty;
if(a){
result = "A is true";
}else{
result = "A is not true";
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果您打算使用第二个块,可以将其简化为:
public string test(){
bool a = true;
if(a){
return "A is true";
}else{
return "A is not true";
}
}
Run Code Online (Sandbox Code Playgroud)
或者进一步:
public string test(){
bool a = true;
return a ? "A is true" : "A is not true";
}
Run Code Online (Sandbox Code Playgroud)
以及类似代码的其他几个迭代(字符串格式化等).