【发布时间】:2021-03-14 08:24:31
【问题描述】:
我有一个班级季节和班级剧集。类 Season 继承类 Episode。 我的课Episode有这个方法:
public void AddView(double rating)
{
viewerCount++;
ratingSum += rating;
if (rating > this.largestRating)
this.largestRating = rating;
}
我的班级季节有一个剧集列表:
public Episode[] episodes { get; private set; }
我覆盖了 Season 类的索引器,因此它返回列表中的索引剧集:
public object this[int i]
{
get { return episodes[i]; }
}
所以当我在程序中这样做时:
Console.WriteLine(season[5]);
Console.WriteLine(episodes[5]);
我得到相同的输出。 同时,当我尝试调用这些情节的方法时,情节[5] 允许我调用函数 AddView,但季节[5] 不允许我这样做。
Severity Code Description Project File Line Suppression State
Error CS1061 'object' does not contain a definition for 'AddView' and no accessible extension
method 'AddView' accepting a first argument of type 'object' could be found (are you missing a using
directive or an assembly reference?) OOP-DZ2 C:\Users\patri\source\repos\OOP-DZ2\OOP-
DZ2\Program.cs 22 Active
如何覆盖索引器,以便访问 Season 对象中的 Episode 对象列表并调用其方法?
已解决 我的索引器被错误地覆盖,它返回对象而不是 Episode 类。谢谢。
【问题讨论】:
-
你的索引器返回一个对象,我猜它应该返回
Episode? -
我认为您正在尝试使用相同的索引器获取对象季节和剧集,对吗?
-
你用了这个关键字,这个引用了当前类,你应该在不同的类上写索引器。