覆盖虚方法

Overriding virtual method

override method的签名和原来的base一样class System.Object, 因为签名只包括方法名和参数的类型和个数

为什么重写方法需要相同的 return 类型?

using System;

namespace Testing_Override_Keyword
{
    class OverridingClass
    {

        public override int ToString()//**Here is error**
        {
            return 1;
        }
    }
}

这是错误

Return type must be string to match overridden member

虚方法ToString()returnstring,但在你的情况下你returnint,这不是相同的签名,因此你有编译错误。

Why it is necessary to having same return type for overriding a method?

从某种意义上说,"because that's what the language specification says"。来自 C# 5 规范第 10.6.4 节:

A compile-time error occurs unless all of the following are true for an override declaration:

  • ...
  • The override method and the overridden base method have the same return type.

从另一种意义上说,"because otherwise it wouldn't make sense"。关键是调用者应该能够调用虚拟方法——包括使用 return 值——而不用关心它是否被覆盖。

想象一下,如果有人写过:

object x = new OverridingClass();
string y = x.ToString();

这将如何与您的覆盖一起使用?