名称为“XYZ”不存在于当前上下文存在 [英] The name 'xyz' does not exist in the current context

查看:110
本文介绍了名称为“XYZ”不存在于当前上下文存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是可能在C#中非常基本的,但我看了看周围很多找到解决的办法。

在我的MVC控制器的操作方法,我有来电routeid( programid ),我需要用它来创建另一个字符串变量( ACCOUNTTYPE )。我有一个的if / else评估 ACCOUNTTYPE 的价值。后来在同样的操作方法的code,我有反璞归真的if / else,是以变量 ACCOUNTTYPE ,并创建一个JSON字符串传递给支付网关。但是,我得到一个错误名称ACCOUNTTYPE在目前的情况下不存在。我是否需要将其声明为public或什么?

下面是两个if / else语句:

 如果(programid == 0)
{
    字符串ACCOUNTTYPE =会员;
}
其他
{
    字符串ACCOUNTTYPE =程序;
}

后来在同一个控制器的动作,我需要使用 ACCOUNTTYPE 变量来计算另一个字符串变量(URL)

 如果(results.Count()0)
{
    字符串的URL = ACCOUNTTYPE +一些文本
}
其他
{
    字符串的URL = ACCOUNTTYPE +其他一些文字
}


解决方案

的问题是,你在你的<$ C $的范围内,定义你的 ACCOUNTTYPE 变量C>如果和其他块,所以它不是这些块之外定义。

尝试声明如果 / 其他块以外的变量:

 字符串ACCOUNTTYPE;
字符串URL;
如果(programid == 0)
{
    ACCOUNTTYPE =会员;
}
其他
{
    ACCOUNTTYPE =程序;
}如果(results.Count()大于0)
{
    URL = ACCOUNTTYPE +一些文本
}
其他
{
    URL = ACCOUNTTYPE +其他一些文字
}

或者,如果你的code是真的这样简单,只需使用条件运营商

 字符串ACCOUNTTYPE = programid == 0? 会员:计划;
字符串的URL = ACCOUNTTYPE +(results.Any()一些文本:其他一些文字);

This is probably really basic in C#, but I looked around a lot to find a solution.

In my MVC controller's action method, I have an incoming routeid (programid) that I need to use to create another string variable (accounttype). I have an if/else to evaluate the value of accounttype. Later in the same action method's code, I have nother if/else that takes the variable accounttype and creates a JSON string to pass to a payment gateway. But I get an error "The name 'accounttype' does not exist in current context.' Do I need to declare it as public or something?

Here are the two if/else statements:

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

Later on in same controller action, I need to use the accounttype variable to calculate another string variable (URL)

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

解决方案

The problem is that you're defining your accounttype variable within the scope of your if and else block, so it's not defined outside of those blocks.

Try declaring your variables outside the if/else blocks:

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"
}

Or if your code is really this simple, just use the conditional operator:

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

这篇关于名称为“XYZ”不存在于当前上下文存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆