【问题标题】:Call different function based on a boolean [duplicate]基于布尔值调用不同的函数[重复]
【发布时间】:2018-03-16 18:55:38
【问题描述】:

我的函数中有一个布尔值来决定调用什么函数。这两个函数都被称为返回一个数组。

现在在我看来Hex[] areaHexes 确实存在,但编译器没有编译,因为它认为它没有设置(不存在)。

如何根据bool semiRandom 的值正确调用这两个函数之一?

void ElevateArea(int q, int r, int range, bool semiRandom = false, float centerHeight = 1f)
{
    Hex centerHex = GetHexAt(q, r);

    if (semiRandom) 
    { 
        Hex[] areaHexes = GetSemiRandomHexesWithinRangeOf(centerHex, range);
    } 
    else
    {
        Hex[] areaHexes = GetHexesWithinRangeOf(centerHex, range);
    }

    foreach (Hex h in areaHexes)
    {
        //if (h.Elevation < 0)
            // h.Elevation =  0;

        h.Elevation += 0.5f * Mathf.Lerp(1f, 0.25f, Hex.Distance(centerHex, h ) / range);
    }
}

【问题讨论】:

  • 您的 areaHexes 在您的 if-else 块中本地声明,它在这些块的范围之外不可见。在外面声明:Hex[] areaHexes; 然后if (semiRandom) { areaHexes = ... } ... 等等。

标签: c#


【解决方案1】:

它不起作用的原因是您当前正在声明两个名为 areaHexes 的局部变量,每个变量都有一个范围,即它们在其中声明的块 - 所以当您尝试时它们都不在范围内使用它们。

Brandon 的回答(在 if 语句之外声明变量,然后从不同的地方分配给它)可以正常工作 - areaHexes 现在在您以后使用它的范围内。但是,您可以更简单地使用条件 ?: 运算符:

Hex[] areaHexes = semiRandom
    ? GetSemiRandomHexesWithinRangeOf(centerHex, range)
    : GetHexesWithinRangeOf(centerHex, range);

【讨论】:

  • 改为这样做。它看起来更漂亮。
【解决方案2】:

您的areaHexes 在您的if-else 块中本地声明,它在这些块的范围之外不可见。你有两个不同的本地 areaHexes 变量:

if (semiRandom) 
{
    // This definition of areaHexes is visible only within these { }
    //   and is not the same as the one in the else block below
    Hex[] areaHexes = GetSemiRandomHexesWithinRangeOf(centerHex, range);
} 
else
{
    // This definition of areaHexes is visible only within these { }
    //   and is not the same one as the one above
    Hex[] areaHexes = GetHexesWithinRangeOf(centerHex, range);
}

在外面声明:

Hex[] areaHexes;

if (semiRandom) { 
    areaHexes = GetSemiRandomHexesWithinRangeOf(centerHex, range);
}
else {
    areaHexes = GetHexesWithinRangeOf(centerHex, range);
}

或者,使用 Jon 显示的第三个 ?: 运算符。

您应该查找 C# 的变量范围规则

【讨论】:

    【解决方案3】:

    在你的条件之前声明你的数组,像这样:

    Hex[] areaHexes;
    
    if (semiRandom) 
    { 
        areaHexes = GetSemiRandomHexesWithinRangeOf(centerHex, range);
    } 
    else
    {
        areaHexes = GetHexesWithinRangeOf(centerHex, range);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      相关资源
      最近更新 更多