简体   繁体   English

使用当前上下文中不存在的未分配局部变量

[英]Use of unassigned local variable that does not exist in current context

I am trying to add the concessionItem price to a list.我正在尝试将优惠商品价格添加到列表中。 I can not access the variable after the for loop is finished, because it is out of scope. for 循环完成后我无法访问该变量,因为它超出了范围。 I've tried writing totalCost above the foreach loop as well, but then it is not accessible within the logic.我也尝试在 foreach 循环上方编写 totalCost,但随后在逻辑中无法访问它。

public void PayForConcessions()
        {
            foreach (ConcessionItem ci in concessionItems)
            {
                decimal totalCost;
                totalCost += ci.Price;
            }

            this.RemoveMoney(totalCost);
        }

you have to assign totalCost and move it before foreach loop你必须分配 totalCost 并在 foreach 循环之前移动它

        decimal totalCost = 0m;
       foreach (ConcessionItem ci in concessionItems)
            {
              
                totalCost += ci.Price;
            }

decimal total cost; needs to be declared inside the method body, but above the loop:需要在方法体内声明,但在循环之上:

public void PayForConcessions()
{
    // HERE
    decimal totalCost;

    foreach (...)
    {
        ...
    }
}

I've tried writing totalCost above the foreach loop as well,我也试过在 foreach 循环上面写 totalCost,

I think you might have put it in the wrong place.. This should be fine:我想你可能把它放在错误的地方..这应该没问题:

    public void PayForConcessions()
    {
        decimal totalCost = 0;
        foreach (ConcessionItem ci in concessionItems)
        {
            totalCost += ci.Price;
        }
        this.RemoveMoney(totalCost);
    }

Basic rule of variable scoping;变量作用域的基本规则; inside the same set of { } brackets, or any nested brackets within, below the point of declaration..在声明点下方的同一组{ }括号内,或其中的任何嵌套括号内..

You can try using Linq and get rid of loop at all:您可以尝试使用Linq并完全摆脱循环:

using System.Linq;

...

public void PayForConcessions() => 
  RemoveMoney(concessionItems.Sum(ci => ci.Price));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM