【问题标题】:Use of unassigned local variable Dictionary使用未赋值的局部变量 Dictionary
【发布时间】:2014-11-21 09:48:17
【问题描述】:

好吧,我一直坚持使用未分配的局部变量。我首先声明我的变量并创建我的字典。

在我的代码下面:

string berichtAantalMunten;
double[] munten = { 2,1,0.50,0.20,0.10,0.05};
Dictionary<double, int> aantalMunten = new Dictionary<double, int>();
int muntenTeller = 0;
double bedragTerug = totaalIngeworpen - prijsDrankje;
foreach (double munt in munten){
    double tijdelijkIngeworpen = totaalIngeworpen - munt;

    if (tijdelijkIngeworpen >= 0)
    {
        muntenTeller++;
        aantalMunten.Add(munt, muntenTeller);
        totaalIngeworpen = tijdelijkIngeworpen;
    }
}

if (aantalMunten.ContainsKey(2))
{
    berichtAantalMunten = aantalMunten[2].ToString() + " x € 2,00\n";
}

if (aantalMunten.ContainsKey(1))
{
    berichtAantalMunten +=  aantalMunten[1].ToString() + " x € 1,00\n";
}

【问题讨论】:

  • 您应该向我们提供有关您的编译错误的更多信息。哪一行有错误?哪个变量在抱怨?
  • @AndrewShepherd 显然是最后一个应该增加 berichtAantalMunten 的地方

标签: c# .net dictionary


【解决方案1】:

在任何情况下,变量berichtAantalMunten 都没有赋值。您可以通过明确分配一个值来修复它。例如通过分配null 或-更合适-"0":

string berichtAantalMunten = "0";

但是,即使它是 string,您也可以像使用 += 的整数一样使用变量

berichtAantalMunten +=  aantalMunten[1].ToString() + " x € 1,00\n";

所以也许你想在计算完值后将其转换为最后的字符串。

【讨论】:

    【解决方案2】:

    问题是第二次调用berichtAantalMunten

    berichtAantalMunten += ...
    

    由于不确定berichtAantalMunten 是否已设置为任何值。一种解决方案是将其初始化为"",或使用StringBuilder 来创建文本。

    【讨论】:

      猜你喜欢
      • 2011-05-05
      • 2014-04-22
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多