gpt4 book ai didi

c# - 列表+结构 : Object reference not set to an instance of an object

转载 作者:行者123 更新时间:2023-11-30 19:47:43 27 4
gpt4 key购买 nike

我在这段代码中遇到了这个错误:

struct Msg
{
public int remove;
public string text;
}

public class Messages
{
#region Class Variables
protected SpriteBatch sb;
List<Msg> msgList;
#endregion

public Messages(SpriteBatch spriteBatch)
{
sb = spriteBatch;
List<Msg> msgList = new List<Msg>();
}

public int Now()
{
return DateTime.Now.Second;
}

public void Add(string text, int keep = 5)
{
Msg temp = new Msg();
temp.remove = Now() + keep;
temp.text = text;
msgList.Add(temp);
}

public void Draw()
{
int count = 0;
foreach (Msg msg in msgList)
{
if (msg.remove >= Now())
{
msgList.Remove(msg);
}
else
{
count++;
sb.DrawString(Game1.SmallFont1, msg.text, new Vector2(10, 5 + count * 25), Color.White);
}
}
}
}

以及执行的确切时间

        msgList.Add(temp);

它给了我:

    NullReferenceException was unhandled
Object reference not set to an instance of an object.

最佳答案

字段msgList未初始化。在构造函数中,您声明并初始化了一个类型为 List<Msg> 的新局部变量。 .

public Messages(SpriteBatch spriteBatch)
{
sb = spriteBatch;
msgList = new List<Msg>(); // correct way
}

关于c# - 列表+结构 : Object reference not set to an instance of an object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6252095/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com