다음 코드 와이 질문에 제공된 제안을 감안할 때이 원래 방법을 수정하고 값이없는 IEnumerable을 반환하지 않으면 IEnumarable에 값이 있는지 확인하기로 결정했습니다.
방법은 다음과 같습니다.
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
});
}
모든 것이 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>();
}
}
위의 방법은 작동하지 않으며 실제로는 그렇지 않습니다. 나는 그것이 내 의도를 설명한다고 생각합니다. 추상 클래스의 인스턴스를 만들 수 없으므로 코드가 작동하지 않도록 지정해야한다고 생각합니다.
다음은 호출 코드입니다. 언제든지 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;
}
}
시간 내 주셔서 감사합니다.
답변
을 사용 list ?? Enumerable.Empty<Friend>()
하거나 FindFriends
돌아올 수 있습니다Enumerable.Empty<Friend>()
답변
당신은 돌아올 수있었습니다 Enumerable.Empty<T>()
.
답변
가장 우아한 방법은 yield break
답변
그것은 물론 개인적인 취향의 문제 일 뿐이지 만, 수익률을 사용 하여이 함수를 작성합니다.
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
}
}
}
}
답변
가장 간단한 방법은
return new Friend[0];
리턴의 요구 사항은 단지 메소드가 구현하는 오브젝트를 리턴하는 것 IEnumerable<Friend>
입니다. 서로 다른 환경에서 IEnumerable을 구현하는 한 두 가지 종류의 객체를 반환한다는 사실은 관련이 없습니다.
답변
public IEnumerable<Friend> FindFriends()
{
return userExists ? 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
}): new List<Friend>();
}
답변
