C#变量已赋值,但从未使用过
我的代码有错误。。我是C#的新手,我正在尝试制作一个基于两人回合的游戏。使用VisualStudio执行此操作 错误为“警告2变量'gs'已赋值,但其值从未使用” 代码如下C#变量已赋值,但从未使用过,c#,visual-studio,C#,Visual Studio,我的代码有错误。。我是C#的新手,我正在尝试制作一个基于两人回合的游戏。使用VisualStudio执行此操作 错误为“警告2变量'gs'已赋值,但其值从未使用” 代码如下 using System.Collections.Generic; using System.Linq; using System.Text; using System; namespace GridWorld { public class newAI : BasePlayer { PlayerWorldState
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace GridWorld
{
public class newAI : BasePlayer
{
PlayerWorldState myWorldState;
private double maxSpeed = 5f;
//public int MaxNumTurn = 15;
private int Steps;
private object count;
public newAI ()
: base()
{
this.Name = "AI FOR GAMES THE A TEAM";
// this.MaxNumTurn = 15;
var gs = new GridSquare.ContentType(); // the variable gs is now a new GridSquare content type
}
void Pathfind()
{
PlayerWorldState startingPoint = BasePlayer(GridSquare.ContentType.Snail);
int myX = 0;
int myY = 0;
if (myX == -1 || myY == -1) // if myX & myY are equal to minus 1 then increment the steps
Steps++;
{
return;
}
gs [myX, myY].Steps = 0; // outside whileloop
while (true)
{
bool madeProgress = false;
foreach (startingPoint mainPoint in gs)
{
int x = mainPoint.X;
int y = mainPoint.Y;
if (SquareOpen(x, y))
{
int passHere = GridSquare[x, y].Steps;
foreach (startingPoint movePoint in ValidMoves(x, y))
{
int myX = movePoint.X;
int myY = movePoint.Y;
int newPass = passHere + 1;
if (GridSquare[myX, myY].Steps > newPass)
{
GridSquare[myX, myY].Steps = newPass;
madeProgress = true;
}
这并不是一个真正的错误。正如它所说,这只是一个警告,说明变量“gs”被分配到某个地方,但从未在任何地方使用过。这不会导致应用程序停止工作。您正在构造函数
newAI
中声明和定义gs
,并试图在Pathfind
中使用它Pathfind
无法看到它,因为它是类构造函数的局部变量,即局部作用域变量。将它像maxSpeed
、Steps
和count
变量一样移动到类中
这只是一个警告,但您的代码至少会有未定义的行为。首先,这不是错误,而是警告。从您的代码中可以清楚地看到这一点。你声明并初始化了一个变量gs的值,但它没有被进一步使用,这意味着编译器会无缘无故地浪费内存。。并在全局范围内声明
gs
以使用它。您找错了位置。此行应给出错误:gs[myX,myY].Steps=0代码>(gs未定义)@UsamaZafar我在代码gs[myX,myY]的这一行上也遇到了此错误。步骤=0;//外部whileloop@Dennis_E是的,这就是我得到错误的地方,这个问题与visual studio有关,我感谢您的帮助。。我已经这样做了,现在我得到了“var”的错误,它说:错误1找不到类型或名称空间名称“var”(是否缺少using指令或程序集引用?@sg82013是的,它会,这是正常的。我建议对C语言进行一些研究。下面是我将给您的最后一个提示,它将使您处于解决此问题的正确位置:。阅读备注部分,查看var
可以使用和不能使用的位置,然后再次查看我的答案。此外,也要研究什么是类型和名称空间,因为您似乎对这些概念不太熟悉。