开发者

Lists + Structs: Object reference not set to an instance of an object

I get this error with this code:

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);
            }
        }
    }
}

and exactly when this is executed

        msgList.Add(temp);
开发者_StackOverflow社区

It gives me:

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


The field msgList is not initialized. In the constructor you declared and initialized a new local variable of type List<Msg>.

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


Don't do this in your constructor:

List<Msg> msgList = new List<Msg>();

You are hiding the msgList field with a method member of the same name (that is, you are redeclaring the name in the constructor). In effect, you never initialize the field.

It should be:

msgList = new List<Msg>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜