在 C# 中覆盖索引器和使用方法

Overriding indexers and using methods in C#

我有 class 季和 class 集。 Class 季继承 class 集。 我的 class 剧集有这个方法:

        public void AddView(double rating)
    {
        viewerCount++;
        ratingSum += rating;
        if (rating > this.largestRating)
            this.largestRating = rating;
    }

我的 class 季有剧集列表:

public Episode[] episodes { get; private set; }

我覆盖了 class 季的索引器,因此 returns 列表中的索引剧集:

        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 对象列表并调用其上的方法?

已解决 我的索引器被错误覆盖,它返回对象而不是 class 剧集。谢谢。

您的class不应该是剧集的基础class,而只是一个容器。事实上,你说“Class Season inherits class Episode”这对我来说没有意义,后来你正确地说“My class Season has a list of episodes”。

I overrided the indexer of class Season so it returns the indexed episode in the list:

public object this[int i]
{
    get { return episodes[i]; }
}

运算符未被覆盖。您重载它们的正常行为以使它们适应您的 class,但它们不会在 C# 意义上被覆盖,即在派生的 class 中重写它们。也许这种混淆让你 return 变成了 object 而不是正确的 class.

public Episode this[int i]
{
    get { return episodes[i]; }
}

Meanwhile, when I try to call methods on those episodes, episodes[5] allows me to call function AddView, but season[5] does not allow me to.

这是正常行为。我猜 episode[5] 是 class Episode 的对象数组,而 Season[5] 只是 return 一个对象。

class Episode {
}

class Season {
    public Episode this[int i]
    {
        get { return episodes[i]; }
    }

    List<Episode> episodes;
}