重载索引器以具有 foreachable 类
我尝试做这样的事情,但这不起作用:
class Garage
{
private List<Car> cars = new List<Car>();
public Car this[int i]
{
get { return cars[i]; }
}
//...
}
Garage g = new Garage();
//get CS1579 - no GetEnumerator definition
foreach (Car c in g)
{
//...
}
正如 MSDN 所说索引器可能会过载,所以我决定在这里询问专家。如何重载索引器以配合 foreach
循环?
I tried to do something like this but this doesn't work:
class Garage
{
private List<Car> cars = new List<Car>();
public Car this[int i]
{
get { return cars[i]; }
}
//...
}
Garage g = new Garage();
//get CS1579 - no GetEnumerator definition
foreach (Car c in g)
{
//...
}
As MSDN says indexers can be overloaded, so I decided to ask experts here. How to overload indexers to cooperate with foreach
loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
foreach
有与索引器无关。您需要声明一个GetEnumerator
方法,该方法返回集合的枚举器。 (当您这样做时,实施IEnumerable< 可能是明智之举;Car>
接口也提供了此方法。)在您的特定情况下,您可以像这样轻松完成:实现
IEnumerable
接口是您可以使用所有 LINQ 扩展方法的接口,例如 < a href="http://msdn.microsoft.com/en-us/library/bb534803.aspx" rel="noreferrer">地点
和选择
,例如:foreach
has nothing to do with indexers. You need to declare aGetEnumerator
method that returns an enumerator for the collection. (While you’re at it, it may be wise to implement theIEnumerable<Car>
interface as well, which provides this method.) In your particular case, you can do it easily like this:A huge benefit of implementing the
IEnumerable<Car>
interface is that you can use all the LINQ extension methods, e.g.Where
andSelect
, for example:您还可以将您的汽车设为私有,并添加公共或内部财产,因为明天在您的车库中您将拥有员工和工具等,
所以你的枚举没有任何意义。
因此,通过以下内容,您无需提供更多代码:
因此您可以在汽车、员工上使用 foreach,如下所示:
You can also make your cars private, and add a public or internal property, because tomorrow in your garage you will have Employees and Tools and so on,
so your enumerate will make no sens.
So with the followings you have no more code to provide :
So you can use foreach, on cars, employees like this: