C#:如何处理循环中在派生 class 中实现但在父 class 中不实现的方法?

C# : How to handle method that is implemented in derived classes but not in the parent class in a loop?

我的 class 中有以下方法:

    public double ComputeCost()
    {
        double Cost = 0;
        foreach (GenericTask Task in this.GenericTasks){
            Cost += Task.Compute();
        }

        return Cost;
        
    }

问题是 Compute 方法仅在 GenericTask 派生的 classes 中实现,例如EngineeringTaskDevelopmentTask 因此上面的代码无法编译。

我怎样才能达到我想要的?我是 C# 的新手,不知道实现此目标的“干净方式”?我是否应该在 GenericTasks 中实现一个虚拟 Compute 方法,尽管它永远不会计算任何东西,因为它缺少适当的数据?

在基础 class 中创建一个抽象方法,并让派生 classes 覆盖该方法。

基础class:

public abstract double Compute();

派生 class:

public override double Compute()
{
    /* your class-specific implementation */
}

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override

https://en.wikipedia.org/wiki/Virtual_function