C# 关于c中的返回语法

C# 关于c中的返回语法,c#,C#,我想知道为什么我需要在下面的代码中输入两次返回语法 public string test(){ bool a = true; if(a){ string result = "A is true"; }else{ string result = "A is not true"; } return result; } 它会出现一个错误,即当前上下文中不存在名称“result” 但无论哪种方式,都存在结果变量。嗯 所以我把代码改成这样 public string test(

我想知道为什么我需要在下面的代码中输入两次返回语法

public string test(){
 bool a = true;
 if(a){
   string result = "A is true";
 }else{
   string result = "A is not true";
 }

  return result;
}
它会出现一个错误,即当前上下文中不存在名称“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;
 }
}
然后它就起作用了。这样使用正确吗

请告诉我


谢谢大家!

您只是缺少代码块中的结果声明。。就我个人而言,我会建议第二个代码块无论如何当更正,但在这里

public string test(){
 bool a = true;
 string result = string.Empty;
 if(a){
   result = "A is true";
 }else{
   result = "A is not true";
 }

  return result;
}
如果你打算使用第二个模块,你可以将其简化为:

public string test(){
 bool a = true;
 if(a){
   return "A is true";
 }else{
   return "A is not true";
 }
}
或进一步:

public string test(){
 bool a = true;

 return a ? "A is true" : "A is not true";
}

以及类似的代码字符串格式等的其他几次迭代。

我非常怀疑您的第二个代码是否真的有效。您在任何时候都没有声明变量结果。请注意,所有这些都与ASP.NET无关—它只是C。您可以说它可以工作,但即使您的第二段代码也是无效的C,除非在其他地方声明了结果。你确定它有效吗?你甚至不需要初始化结果。