Ser*_*pia 310 c# ienumerable
鉴于以下代码和此问题中给出的建议,我决定修改这个原始方法,并询问IEnumarable中是否有任何值返回它,如果没有返回没有值的IEnumerable.
这是方法:
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
});
}
Run Code Online (Sandbox Code Playgroud)
由于一切都在return语句中,我不知道如何做到这一点.会这样的吗?
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>();
}
}
Run Code Online (Sandbox Code Playgroud)
上面的方法不起作用,事实上它不应该; 我觉得这说明了我的意图.我觉得我应该指定代码不起作用,因为你不能创建一个抽象类的实例.
这是调用代码,我不希望它随时接收null IEnumerable:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
感谢您的时间.
Mic*_*zek 544
您可以使用list ?? Enumerable.Empty<Friend>(),或FindFriends返回Enumerable.Empty<Friend>()
Pav*_*syn 97
至于我,最优雅的方式是 yield break
小智 8
这当然只是个人偏好的问题,但我会使用yield return来编写这个函数:
public IEnumerable<Friend> FindFriends()
{
//Many thanks to Rex-M for his help with this one.
//http://stackoverflow.com/users/67/rex-m
if (userExists)
{
foreach(var user in doc.Descendants("user"))
{
yield return new Friend
{
ID = user.Element("id").Value,
Name = user.Element("name").Value,
URL = user.Element("url").Value,
Photo = user.Element("photo").Value
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
131023 次 |
| 最近记录: |