c# - 无法反转列表内部 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'
我该如何解决这个问题?
解决方案
有两种Reverse
方法可以考虑:
- 实例方法
List<T>.Reverse()
就地反转列表,但具有void
返回类型。 - 扩展方法
Enumerable.Reverse<T>()
不会修改数据源,而是返回数据的反向“视图”。
编译器仅在用尽实例方法后才查找扩展方法 - 所以在这种情况下,它绑定到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())
{
...
}
推荐阅读
- angular - Angular:解析自定义打字稿装饰器
- angular - Notify second message after first message is hidden
- ios - CAEmitterCell 在一段时间后自动停止发射
- angular - 根据 Angular 中的下拉值呈现不同的图表
- signal-processing - 断点列表应该在去趋势 EEG 信号中
- amazon-web-services - 属性 ID 不能为空 aws cloudformation
- eclipse - Toolbar in Part Descriptor in eclipse 4
- c++ - Is !NaN not a NaN?
- python - How to get entities with direction in relation extraction?
- ruby - What is the argument passed into RSpec's double method used for?