字段永远不会被分配,并且始终具有默认值null

本文关键字:null 默认值 永远 分配 字段 | 更新日期: 2023-09-27 18:09:53

我得到这个错误对不起,所有这一切,我需要改变的值和不知道这是怎么回事怎么改变null

的值

字段永远不会被赋值,并且始终具有默认值null

GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
//  this is ling gives me field is never assigned to and will alwayhave defult value nulls c#
Texture2D marioTexture;
int marioYPos=100;
int marioXPos=100;
int marioWidth=64;
int marioHeight=64;
// and this line give me field is never assigned to and will alwayhave defult value nulls c#
Texture2D PongBallFinalTexture;
int PongBallFinalYpos=50;
int PongBallFinalXpos=50;
int PongBallFinalWidth=32;
int PongBallFinalHeight=32;
graphics.GraphicsDevice.Clear (Color.CornflowerBlue);
spriteBatch.Begin ();
spriteBatch.Draw (marioTexture, new Rectangle (marioXPos, marioYPos, marioWidth, marioHeight), Color.White);
base.Draw (gameTime);
spriteBatch.Draw (PongBallFinalTexture, new Rectangle (PongBallFinalXpos, PongBallFinalYpos, PongBallFinalWidth, PongBallFinalHeight), Color.White);
base.Draw (gameTime);
spriteBatch.End ();

字段永远不会被分配,并且始终具有默认值null

好吧,在你发布的代码,你从来没有分配任何值给这两个字段给出错误,你只是声明他们。c#中不允许使用未初始化的变量。

要使它工作,你需要赋值,就像你在那里对位置和大小所做的一样。例如直接在声明中:

Texture2D marioTexture = new Texture2D(graphics.GraphicsDevice, marioWidth, marioHeight);
Texture2D PongBallFinalTexture = new Texture2D(graphics.GraphicsDevice, PongBallFinalWidth, PongBallFinalHeight);

或后面的程序,与声明分开,但在使用它们之前:

Texture2D marioTexture;
Texture2D PongBallFinalTexture;
...
marioTexture = new Texture2D(graphics.GraphicsDevice, marioWidth, marioHeight);
PongBallFinalTexture = new Texture2D(graphics.GraphicsDevice, PongBallFinalWidth, PongBallFinalHeight);

使用基本构造函数。这只是一个例子,你必须知道你想如何构建纹理,给它们分配什么。