首页 > 解决方案 > 不能在此范围内声明名为“nextjunction”的本地或参数,因为该名称在封闭的本地范围中用于定义本地

问题描述

我正在 Windows 窗体应用程序中创建游戏。游戏的基本前提是用户围绕二维鸟瞰图控制汽车。我创建了一个名为的类junction,它指示 2 条或更多条道路的交汇点,用户可以根据可用选项在路口转弯车辆。当汽车到达一个路口时,通过下面的代码计算汽车保证会遇到的下一个路口。但是,我收到一个错误,不允许我将计算的 junction 重新分配给变量nextjunction

不能在此范围内声明名为“nextjunction”的本地或参数,因为该名称在封闭的本地范围中用于定义本地

// nextjunction.north is a class attribute of "junction" stored as a Boolean
// which determines if there is potential for the car to move north or not.
// Same goes for other directions.

// nextjunction.northjunc is a class attribute of "junction" stored as a
// junction which indicates the first junction immediately north of the 
// given junction. Same goes for other directions, 
// eg. nextjunction.southjunc indicates the first junction immediately
// south of nextjunction.

if (nextusermove == "north" && nextjunction.north==true)
{
    junction nextjunction = nextjunction.northjunc;
}
else if (nextusermove == "east" && nextjunction.east == true)
{
    junction nextjunction = nextjunction.eastjunc;
}
else if (currentmove == "down" && nextjunction.south == true)
{
    junction nextjunction = nextjunction.southjunc;
}
else if (currentmove == "west" && nextjunction.west == true)
{
    junction nextjunction = nextjunction.westjunc;
}

//the error occurs on every line of nextjunction assignment

我想nextjunction正确分配。

标签: c#

解决方案


这是一个循环引用,将不起作用...

junction nextjunction = nextjunction.northjunc;

nextjunction不能实例化,同时从自身的属性设置其值。

我会考虑重命名您的属性,请注意我已重命名nextjunctioncurrentjunction. 你没有发布你所有的代码,所以我看不到你是如何实例化nextjunction我重命名为的 s 的currentjuction,也就是说,试试这个......

junction nextjunction;
if (nextusermove == "north" && currentjunction.north == true)
{
    nextjunction = currentjunction.northjunc;
}
else if (nextusermove == "east" && currentjunction.east == true)
{
    nextjunction = currentjunction.eastjunc;
}
else if (currentmove == "down" && currentjunction.south == true)
{
    nextjunction = currentjunction.southjunc;
}
else if (currentmove == "west" && currentjunction.west == true)
{
    nextjunction = currentjunction.westjunc;
}

推荐阅读