从if / else语句中获取值?

时间:2013-10-20 17:34:09

标签: c# if-statement scope

如果我有一系列这样的if / else语句,我想得到一个特定的值,那么我如何在等式之外访问该值?我让所有内容都通过命令提示符,并且没有其他任何课程。

if (shippingInput == 1)
{
    double shippingAmount = shippingDetails * 3;
}
else if (shippingInput == 2)
{
    double shippingAmount = shippingDetails * 4;
}
else
{
    double shippingAmount = shippingDetails * 5.5;
}

我的代码即将结束

double shippingCost = shippingAmount + surcharge;

但是它的名字是' shippingAmount'和'附加费'在当前上下文中不存在。

感谢您的帮助!我还没有标记答案,但是在if / else括号之外声明语句并从每个语句中删除双重语句后,它完美地运行了。

6 个答案:

答案 0 :(得分:3)

每次都在制作新的变量。像这样宣布一次:

double shippingAmount;

if (shippingInput == 1)
{
    shippingAmount = shippingDetails * 3;
}
else if (shippingInput == 2)
{
    shippingAmount = shippingDetails * 4;
}
else
{
    shippingAmount = shippingDetails * 5.5;
}

答案 1 :(得分:2)

你需要在语句之外定义变量。

double shippingAmount;


/*some more logic*/

if (shippingInput == 1)
{
    shippingAmount = shippingDetails * 3;
}
else if (shippingInput == 2)
{
    shippingAmount = shippingDetails * 4;
}
else
{
    shippingAmount = shippingDetails * 5.5;
}

通过在if / else语句中定义变量,它们只存在于大括号上下文中,因此一旦您退出代码块,就无法访​​问它们。

答案 2 :(得分:1)

在语句之前声明您的变量,使用默认值(来自逻辑的else部分):

double shippingAmount = shippingDetails * 5.5;
if (shippingInput == 1)
{
    shippingAmount = shippingDetails * 3;
}
else if (shippingInput == 2)
{
    shippingAmount = shippingDetails * 4;
}

答案 3 :(得分:0)

您必须在if / else范围内声明shippingAmount

double shippingAmount = 0;

if (shippingInput == 1)
{
    shippingAmount = shippingDetails * 3;
}
else if (shippingInput == 2)
{
    shippingAmount = shippingDetails * 4;
}
else
{
    shippingAmount = shippingDetails * 5.5;
}

答案 4 :(得分:0)

你就是这样做的。

var shippingAmount = (shippingInput == 1) ? shippingDetails * 3 :
                     (shippingInput == 2) ? shippingDetails * 4 :
                                            shippingDetails * 5.5;

答案 5 :(得分:0)

您可以将代码改进为DRY,如下所示:

float multiplier;

switch(shippingInput)
{
    case 1: multiplier = 3; break;
    case 2: multiplier = 4; break;
    default: multiplier = 5.5;
}

double shippingAmount = shippingDetails * multiplier;