首页 > 解决方案 > 无法反转列表内部 foreach

问题描述

我有一个List<T>需要反转的,所以我尝试了:

foreach (Round round in Competition.Rounds.Reverse())
{

}

这将返回以下错误:

the foreach statement can not work with variables of type 'void' 
   because 'void' does not contain a public instance definition for 'GetEnumerator' 

我该如何解决这个问题?

标签: c#

解决方案


有两种Reverse方法可以考虑:

编译器仅在用尽实例方法后才查找扩展方法 - 所以在这种情况下,它绑定到List<T>.Reverse()方法......这就是它无法编译的原因。(你不能迭代void。)

如果要修改列表,只需单独调用该方法即可:

Competition.Rounds.Reverse();
foreach (Round round in Competition.Rounds)
{
    ...
}

如果不想修改列表,最简单的方法大概就是Enumerable.Reverse<T>直接调用:

foreach (Round round in Enumerable.Reverse(Competition.Rounds))
{
    ...
}

或者您可以有效地“丢失” 的编译时类型List<T>,例如:

// Important: don't change the type of rounds to List<Round>
IEnumerable<Round> rounds = Competition.Rounds;
foreach (Round round in rounds.Reverse())
{
    ...
}

推荐阅读