【发布时间】:2013-12-15 03:44:45
【问题描述】:
我在父类中定义了ToString(),其方式几乎适用于其所有子类,这通常涉及调用名为Name 的属性。该属性在子类中重新定义。
但是,这不起作用,因为始终使用父类的 Name 属性,即使我在后代类中重新定义它也是如此。
这是一个例子:
using System;
namespace test
{
class Program
{
static void Main(string[] args)
{
Bar n = new Bar();
Console.WriteLine(n);
Console.ReadLine();
}
}
class Foo
{
public override string ToString()
{
return MyName;
}
public string MyName { get { return "foo"; }}
}
class Bar : Foo
{
public new string MyName { get { return "bar"; }}
}
}
这个例子的输出是foo,但我希望它是bar。
我做错了什么?还是我只是误解了 C# 中继承的一个基本方面?
【问题讨论】:
标签: c# inheritance