当前上下文中不存在名称“xyz”

这在C#中可能是非常基础的,但我环顾四周寻找解决方案。

在我的MVC控制器的action方法中,我有一个传入的routeid(programid),我需要用它来创建另一个字符串变量( accounttype )。 我有一个if / else来评估accounttype的值。 稍后在同一个动作方法的代码中,我还有if / else接受变量accounttype并创建一个JSON字符串以传递给支付网关。 但是我收到一个错误"The name 'accounttype' does not exist in current context.' 我需要将其声明为公共或其他内容吗?

以下是两个if / else语句:

 if (programid == 0) { string accounttype = "Membership"; } else { string accounttype = "Program"; } 

稍后在同一控制器操作中,我需要使用accounttype变量来计算另一个字符串变量(URL)

 if (results.Count() > 0) { string URL = accounttype + "some text" } else { string URL = accounttype + "some other text" } 

问题是您在ifelse块的范围内定义了您的accounttype变量,因此它没有在这些块之外定义。

尝试在if / else块之外声明变量:

 string accounttype; string URL; if (programid == 0) { accounttype = "Membership"; } else { accounttype = "Program"; } if (results.Count() > 0) { URL = accounttype + "some text" } else { URL = accounttype + "some other text" } 

或者,如果您的代码真的很简单,只需使用条件运算符 :

 string accounttype = programid == 0 ? "Membership" : "Program"; string URL = accounttype + (results.Any() ? "some text" : "some other text"); 

范围是你的问题:)

因为我猜你是新手,我会尝试用简单的词来定义它:变量的范围是变量所在的位置。 并非所有变量都可以在程序中随处调用,我们称之为全局变量。

在您的情况下,您在if .. else语句中声明这些变量,并且,由于C#规则,它们会在if块结束时立即死亡。 这就是编译器告诉你的:你不能调用不存在的东西。

要解决您的问题,您只需要声明

 string accounttype; 

if.. else之前,你会没事的。

如果您想了解更多关于范围的信息, 这是一个很好的起点!

accounttype的范围仅限于if语句。 做

 string accounttype; if (programid == 0) { accounttype = "Membership"; } else { accounttype = "Program"; } 

这是一个范围问题。 大括号{}内的任何内容都被定义为块。 块中定义的任何变量仅在该块中可用,并在退出块时进行垃圾回收。

不要在if语句的块内定义accountType:

 string accounttype; if (programid == 0) { accounttype = "Membership"; } else { accounttype = "Program"; } 

你的范围不正确,试试这个:

 string accounttype; if (programid == 0) { accounttype = "Membership"; } else { accounttype = "Program"; } 

帐户类型变量的范围在if的{ }中。 你需要在if之后声明变量,以便能够在之后使用它,甚至更好:

 string accounttype = programid == 0 ? "Membership" : "Program"; 

因为您在闭包中定义变量,所以一旦退出这些闭包,它们就会超出范围。 你需要:

 string URL; if(test) { URL = "1"; } else { URL = "2"; }