我似乎已经陷入了一些巨大的,巨大的麻烦NullReferenceException异常 [英] I seem to have fallen into some massive, massive trouble with NullReferenceExceptions

查看:150
本文介绍了我似乎已经陷入了一些巨大的,巨大的麻烦NullReferenceException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我开发了解析,并从网站显示的XML信息的软件。够简单吧?

Recently I'm developing a software that parses and displays XML information from a website. Simple enough right?

我收到NullReferenceException异常负荷。例如,此方法:

I'm getting LOADS of NullReferenceExceptions. For example, this method:

private void SetUserFriends(List<Friend> list)
{
    int x = 40;
    int y = 3;

    if (list != null)
    {
        foreach (Friend friend in list)
        {
            FriendControl control = new FriendControl();
            control.ID = friend.ID;
            control.URL = friend.URL;
            control.SetID(friend.ID);
            control.SetName(friend.Name);
            control.SetImage(friend.Photo);

            control.Location = new Point(x, y);
            panel2.Controls.Add(control);

            y = y + control.Height + 4;
        } 
    }
}

我不得不为了包装一个丑陋的罪过。如果各地的实际foreach循环prevent一个例外。

I had to wrap an ugly as sin If around the actual foreach loop in order to prevent an exception.

我觉得我只是把对轮胎漏气创可贴,而不是真正解决了这个问题。有没有什么办法可以解决这个问题?也许一本书,我应该阅读有关的编程模式,还是什么呢?

I feel I'm just putting bandaids on a flat tire instead of actually fixing the problem. Is there any way I can tackle this problem? Maybe a book I should read regarding programming patterns or what not?

说真的,我迷路了。我可能问错了问题。

Really, I'm lost. I'm probably asking the wrong questions.

推荐答案

听起来好像你不确定,如果你收到你的方法不好的参数做什么。没有什么内在的错误,你在做什么了,但更常见的模式是在方法的头部,检查参数,抛出一个异常,如果他们是你期待不算什么:

It sounds as if you're unsure what to do if you receive bad parameters in your methods. There's nothing inherently wrong with what you're doing now, but the more common pattern is to check parameters in the head of your method, throwing an exception if they're not what you're expecting:

if (list == null)
{
    throw new ArgumentNullException(list);
}

这是一个共同的防御性编程模式 - 检查,以确保您所提供的数据通过基本的完整性检查

This is a common defensive programming pattern - check to make sure that the data you're provided passes basic sanity checks.

现在,如果你调用此方法明确你自己,你发现这个方法接收一个空列表当你没有预料到的参数,它的时间看调用方法的逻辑。我自己,我preFER传递一个空列表时,我有没有元素,而不是,以避免特殊情况下,如此。

Now, if you're calling this method explicitly yourself, and you're finding this method receiving a null list parameter when you're not expecting it, it's time to look at the logic of the calling method. Myself, I prefer to pass an empty list when I have no elements, as opposed to null, to avoid special cases such as this.

这篇关于我似乎已经陷入了一些巨大的,巨大的麻烦NullReferenceException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆