【发布时间】:2011-02-18 18:44:30
【问题描述】:
我在浏览 C# Brainteasers (http://www.yoda.arachsys.com/csharp/teasers.html) 时遇到了一个问题:这段代码的输出应该是什么?
class Base
{
public virtual void Foo(int x)
{
Console.WriteLine ("Base.Foo(int)");
}
}
class Derived : Base
{
public override void Foo(int x)
{
Console.WriteLine ("Derived.Foo(int)");
}
public void Foo(object o)
{
Console.WriteLine ("Derived.Foo(object)");
}
}
class Test
{
static void Main()
{
Derived d = new Derived();
int i = 10;
d.Foo(i); // it prints ("Derived.Foo(object)"
}
}
但是如果我把代码改成
class Derived
{
public void Foo(int x)
{
Console.WriteLine("Derived.Foo(int)");
}
public void Foo(object o)
{
Console.WriteLine("Derived.Foo(object)");
}
}
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
int i = 10;
d.Foo(i); // prints Derived.Foo(int)");
Console.ReadKey();
}
}
我想知道为什么当我们继承而不是继承时输出会发生变化;为什么在这两种情况下方法重载的行为不同?
【问题讨论】:
标签: c# inheritance overloading