Với mã sau và các gợi ý được đưa ra in this question, tôi đã quyết định sửa đổi phương thức gốc này và hỏi xem có bất kỳ giá trị nào trong IEnumarable trả về nó, nếu không trả về một IEnumerable không có giá trị.Làm thế nào tôi có thể trả về một IEnumerable trống?
Đây là phương pháp:
public IEnumerable<Friend> FindFriends()
{
//Many thanks to Rex-M for his help with this one.
//https://stackoverflow.com/users/67/rex-m
return doc.Descendants("user").Select(user => new Friend
{
ID = user.Element("id").Value,
Name = user.Element("name").Value,
URL = user.Element("url").Value,
Photo = user.Element("photo").Value
});
}
Kể từ khi tất cả mọi thứ ở bên trong câu lệnh return, tôi không biết làm thế nào tôi có thể làm điều này. Có công việc nào như vầy không?
public IEnumerable<Friend> FindFriends()
{
//Many thanks to Rex-M for his help with this one.
//https://stackoverflow.com/users/67/rex-m
if (userExists)
{
return doc.Descendants("user").Select(user => new Friend
{
ID = user.Element("id").Value,
Name = user.Element("name").Value,
URL = user.Element("url").Value,
Photo = user.Element("photo").Value
});
}
else
{
return new IEnumerable<Friend>();
}
}
Phương pháp trên không có tác dụng và trên thực tế, phương pháp này không được giả định; Tôi chỉ cảm thấy nó minh họa ý định của tôi. Tôi cảm thấy tôi nên xác định rằng mã không hoạt động vì bạn không thể tạo một thể hiện của một lớp trừu tượng.
Đây là mã gọi điện thoại, tôi không muốn nó nhận được một null IEnumerable bất cứ lúc nào:
private void SetUserFriends(IEnumerable<Friend> list)
{
int x = 40;
int y = 3;
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;
}
}
Cảm ơn bạn đã dành thời gian.
Nhìn vào mã ở đây bạn nên sử dụng yield return và phá vỡ năng suất. –