【发布时间】:2010-07-12 03:50:15
【问题描述】:
最近我正在开发一种软件,可以解析和显示来自网站的 XML 信息。够简单吧?
我收到大量 NullReferenceExceptions。比如这个方法:
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 循环周围包裹一个丑陋的 as sin If。
我觉得我只是在爆胎上贴了创可贴,而不是真正解决问题。有什么办法可以解决这个问题吗?也许我应该读一本关于编程模式的书还是什么?
真的,我迷路了。我可能问错了问题。
【问题讨论】:
-
您应该查看调用
SetUserFriends的代码。如果您假设朋友列表不应该是null(我会说这是一个足够公平的假设),那么错误就在于传递 innull的任何内容。遇到异常时使用调试器查找调用堆栈。 -
最好检查一下为什么你有一个空的 List 引用而不是一个空的 List 对象。
-
这是一个旁注,但我主张接受 IEnumerable
,因此该方法不需要调用者使用特定的集合类。 -
@Steven 如果你需要列表功能,至少是一个 IList
-
@Darko:是的,当然。无论最低限度足够的接口是什么。
标签: c# .net nullreferenceexception