如何将对象添加到另一个对象内的列表(或其他集合)?
我有这个:
public class Room
{
public string RoomID { get; set; }
public string RoomName { get; set; }
public List<User> UsersInRoom { get; set; }
//public IDuplexClient RoomCallbackChannel { get; set; }
}
如您所见,有一个包含房间中用户的列表。
但要真正使其工作,我需要添加用户,所以我这样做了:
User usr;
Room roomi;
if (userNameTest == null)
{
lock (_clients)
{
usr = new User { UserID = sessionID, CallbackChannel = client, UserName = userName };
roomi = new Room();
roomi.RoomID = sessionID;
roomi.RoomName = room;
roomi.UsersInRoom.Add(usr);
//roomi.UsersInRoom.Add(usr);
_rooms.Add(roomi);
//_clients.Add(usr);
}
}
并在行:
roomi.UsersInRoom.Add(usr);
我得到 NullReferenceException。 这是怎么回事 ?
I have this:
public class Room
{
public string RoomID { get; set; }
public string RoomName { get; set; }
public List<User> UsersInRoom { get; set; }
//public IDuplexClient RoomCallbackChannel { get; set; }
}
As you can see there is an List that contains users in room.
But to actually make it work I need to add users, so I did this:
User usr;
Room roomi;
if (userNameTest == null)
{
lock (_clients)
{
usr = new User { UserID = sessionID, CallbackChannel = client, UserName = userName };
roomi = new Room();
roomi.RoomID = sessionID;
roomi.RoomName = room;
roomi.UsersInRoom.Add(usr);
//roomi.UsersInRoom.Add(usr);
_rooms.Add(roomi);
//_clients.Add(usr);
}
}
and at line:
roomi.UsersInRoom.Add(usr);
I get NullReferenceException.
What's going on ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您尚未创建列表 - 因此
roomi.UsersInRoom
为 null。您可以通过将该行更改为来解决此问题:
请注意,如果您使用的是 C# 3 或更高版本,则可以使用对象和集合初始值设定项来简化所有这些代码。此外,您还可以将
UsersInRoom
设为只读属性,将值设置为Room
构造函数(或变量初始值设定项)内的新列表。不幸的是,我现在没有时间展示所有这些,但对于对象/集合初始化程序来说,类似这样:
如果您更改它,以便由 Room 本身初始化
UsersInRoom
,则这将更改为:You haven't created a list - so
roomi.UsersInRoom
is null.You could fix this by changing the line to:
Note that if you're using C# 3 or higher, you can use object and collection initializers to make all of this code simpler. Additionally, you could potentially make
UsersInRoom
a read-only property, setting the value to a new list within aRoom
constructor (or a variable initializer).Unfortunately I don't have time to show all of this right now, but something like this for the object/collection initializers:
If you change it so that
UsersInRoom
is initialized by Room itself, this changes to:List
,是一个引用类型。引用类型的默认值为null
。在开始向列表添加项目之前,您需要初始化列表。
List<T>
, is a reference type. The default value for a reference type isnull
.You need to initialise the List before you start adding items to it.
您确定
List
已初始化吗?列表是一个对象,因此您必须“创建”它,如下所示:Have you made sure the
List
is initialized? List is an object so you have to 'create' it, like so: