【问题标题】:C# cannot override inherited memberC# 不能覆盖继承的成员
【发布时间】:2015-02-14 12:31:51
【问题描述】:

我正在从一本名为 Chegwidden Gladdis 的书中学习 C#。我正在制作与书中所写相同的程序和相同的代码。但有一个问题。我不能覆盖父类的方法。我从一章开始就完全阅读了这本书,5遍,一切都一样,但我不明白为什么我不能覆盖父类的方法。这是来自基类 PassFailActivity.cs 的代码

using System;
namespace ProtectedMembers
{
    public class PassFailActivity : GradedActivity2
    {
        private double minPassingScore; // Minimum passing score

        /// <summary>
        /// The constructor sets the minimum passing score
        /// </summary>
        /// <param name="mps">The minimum passing score.</param>
        public PassFailActivity(double mps)
        {
            minPassingScore = mps;
        }

        /// <summary>
        /// The GetGrade method returns a letter grade determined
        /// from the score field. This methos overrides the base class method.
        /// </summary>
        /// <returns>The letter grade</returns>
        public override char GetGrade()
        {
            char letterGrade;

            if (base.GetScore() >= minPassingScore)
                letterGrade = 'P';
            else
                letterGrade = 'F';

            return letterGrade;
        }
    }
}

和 GradedActivity2.cs

using System;

namespace ProtectedMembers
{
    public class GradedActivity2
    {
        protected double score; // Numberic score

        /// <summary>
        /// The SetScore method sets the score field.
        /// </summary>
        /// <param name="s">The value to store in score</param>
        public void SetScore(double s)
        {
            score = s;
        }

        /// <summary>
        /// The GetScore method returns the score.
        /// </summary>
        /// <returns>The value stored in the score field</returns>
        public double GetScore()
        {
            return score;
        }

        /// <summary>
        /// The GetGrade method returns a letter grade determined from the score field.
        /// </summary>
        /// <returns>Return the letter grade</returns>
        public char GetGrade()
        {
            char letterGrade;

            if (score >= 90)
                letterGrade = 'A';
            else if (score >= 80)
                letterGrade = 'B';
            else if (score >= 70)
                letterGrade = 'C';
            else if (score >= 60)
                letterGrade = 'D';
            else
                letterGrade = 'F';

            return letterGrade;
        }
    }
}

和通过失败考试

using System;

namespace ProtectedMembers
{
    public class PassFailExam : PassFailActivity
    {
        private int numQuestions; // Number of questions
        private double pointsEach; // Points for each question
        private int numMissed; // Number of questions missed

        /// <summary>
        /// The constructor sets the number of questions, the number
        /// of questions missed, and the minimum passing score.
        /// </summary>
        /// <param name="questions">The number of questions</param>
        /// <param name="missed">The number of questions missed</param>
        /// <param name="minPassing">The minimum passing score</param>
        public PassFailExam(int questions, int missed, double minPassing) : base(minPassing)
        {
            // Declare a local variable for the score.
            double numericScore;

            // Set the numQuestions and numMissed fields.
            numQuestions = questions;
            numMissed = missed;

            // Calculate the points for each questions and the numeric score for this exam.
            pointsEach = 100.0 / questions;
            numericScore = 100.0 - (missed * pointsEach);

            // Call the base class's SetScore method to set the mumeric score.
            SetScore(numericScore);
        }

        /// <summary>
        /// The GetpointsEach method returns the number of points each questions is worth
        /// </summary>
        /// <returns>The value in the pointsEach field</returns>
        public double GetPointsEach()
        {
            return pointsEach;
        }

        /// <summary>
        /// The GetNumMissed method returns the number of questions missed
        /// </summary>
        /// <returns>The value in the numMissed field</returns>
        public int GetNumMissed()
        {
            return numMissed;
        }
    }
}

这是我的主要内容

using System;

namespace ProtectedMembers
{
    public class PassFailExamDemo
    {
        public static void Main111()
        {
            int questions, // Number of questions
                missed; // Number of questions missed
            double minPassing; // Minmum passing score

            // Get the number of questions on the exam
            Console.Write("How many questions are " + "on the exam? ");
            questions = Convert.ToInt32(Console.ReadLine());

            // Get the number of questions missed.
            Console.Write("How many questions did " + "the student miss? ");
            missed = Convert.ToInt32(Console.ReadLine());

            // Get the minimum passing score
            Console.Write("What is the minimum " + "passing score? ");
            minPassing = Convert.ToInt32(Console.ReadLine());

            // Create a PassFailExam project
            PassFailExam exam = new PassFailExam(questions, missed, minPassing);

            // Display the teset results.
            Console.WriteLine("Each questions counts {0} points.",
                exam.GetPointsEach());
            Console.WriteLine("The exam score is {0} ",
                exam.GetScore());
            Console.WriteLine("The exam grade is {0} ",
                exam.GetGrade());
            Console.ReadLine();
        }
    }
}

输出应该是

How many questions are on the exam? 100
How many questions did the student miss? 25
What is the minimum passing score? 60
Each question counts 1 points.
The exam score is 75
The exam grade is P

我尝试将基本方法设为虚拟并在尝试覆盖它时调用覆盖,这只会让我出现这个错误“'ProtectedMembers.PassFailActivity.GetGrade()': cannot override继承的成员'ProtectedMembers.GradedActivity2.GetGrade() ' 因为它没有被标记为虚拟、抽象或覆盖”。我完全检查了

【问题讨论】:

  • 您需要在继承树的根类中将GetGrade设为虚拟。
  • 您需要尝试仅包含与您的问题相关的代码,您似乎已经包含了您拥有的所有代码,这使得很难确定问题出在哪里

标签: c# object inheritance base


【解决方案1】:

错误是不言自明的,在GradedActivity2中标记函数virtual

public virtual char GetGrade()

来自 MSDN:

virtual 关键字用于修改方法、属性、索引器或 事件声明并允许它在派生中被覆盖 班级。例如,这个方法可以被任何类覆盖 继承它:

【讨论】:

  • 谢谢。对不起,我没有在 MSDN 上搜索它
  • 显然我不能说“+1 The error is self-explanatory
  • 如果你理解关键字Virtual you will not day 错误不是不言自明,确实是
  • msdn.microsoft.com/en-us/library/9fkccyh4.aspx 供任何想要快速参考的人参考
  • 如果错误是不言自明的,prouser135 就不会问这个问题,我也不必谷歌它。
【解决方案2】:

您在基类中的方法GetGrade 应该告诉它允许派生,使用virtual 关键字:

public virtual char GetGrade()

这只是一种故障安全机制,也是一种优化,因为在派生类中不必对派生方法检查非虚拟方法。

【讨论】:

  • OH FSCK,这就像在 Turbo Pascal 中,完全是 Java™ 的退步,因此如果您需要覆盖系统行为,☹ 和 非常 很烦人......
猜你喜欢
  • 1970-01-01
  • 2020-08-18
  • 1970-01-01
  • 2016-01-19
  • 1970-01-01
  • 2013-06-30
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多