public class CategoryNavItem
{
public int ID { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public CategoryNavItem(int CatID, string CatName, string CatIcon)
{
ID = CatID;
Name = CatName;
Icon = CatIcon;
}
}
public static List<Lite.CategoryNavItem> getMenuNav(int CatID)
{
List<Lite.CategoryNavItem> NavItems = new List<Lite.CategoryNavItem>();
-- Snipped code --
return NavItems.Reverse();
}
反过来不起作用:
Error 3 Cannot implicitly convert type 'void' to 'System.Collections.Generic.List<Lite.CategoryNavItem>'
为什么会出现这种情况?
答案 0 :(得分:125)
尝试:
NavItems.Reverse();
return NavItems;
List<T>.Reverse()
是就地反向;它不会返回新列表。
这个 与LINQ形成对比,其中Reverse()
返回相反的序列,但是当有一个合适的非扩展方法时,它总是优先选择扩展方法。另外,在LINQ案例中,它必须是:
return someSequence.Reverse().ToList();
答案 1 :(得分:84)
一种解决方法是Return NavItems.AsEnumerable().Reverse();
答案 2 :(得分:18)
.Reverse()
会反转列表中的项目,但不会返回新的反转列表。
答案 3 :(得分:8)
Reverse()
不会返回反转列表本身,它会修改原始列表。所以重写如下:
return NavItems.Reverse();
要
NavItems.Reverse();
return NavItems;
答案 4 :(得分:6)
Reverse()
不会按预期函数返回List。
NavItems.Reverse();
return NavItems;
答案 5 :(得分:3)
.Reverse
撤销“就地”......,尝试
NavItems.Reverse();
return NavItems;
答案 6 :(得分:2)
如果您有一个示例中的列表:
List<Lite.CategoryNavItem> NavItems
您可以使用通用的Reverse <>扩展方法来返回新列表,而无需修改原始列表。只需使用如下扩展方法:
List<Lite.CategoryNavItem> reversed = NavItems.Reverse<Lite.CategoryNavItem>();
注意:您需要指定<>通用标记以显式使用扩展方法。 别忘了
using System.Linq;
答案 7 :(得分:-1)
如果你:
someList.Reverse()
,因为它不返回任何内容 (void
)someList.Reverse()
,因为它会修改源列表someList.AsEnumerable().Reverse()
并得到 Ambiguous invocation
错误你可以试试Enumerable.Reverse(someList)
。
不要忘记:
using System.Linq;