【发布时间】:2023-03-12 12:25:02
【问题描述】:
interface IBase
{
string Name { get; }
}
class Base : IBase
{
public Base() => this.Name = "Base";
public string Name { get; }
}
class Derived : Base//, IBase
{
public Derived() => this.Name = "Derived";
public new string Name { get; }
}
class Program
{
static void Main(string[] args)
{
IBase o = new Derived();
Console.WriteLine(o.Name);
}
}
在这种情况下,输出将是“Base”。
如果我明确声明 Derived 实现了 IBase(实际上它已经由基类 Base 实现,并且这样的注释似乎没用)输出将是“Derived”
class Derived : Base, IBase
{
public Derived() => this.Name = "Derived";
public new string Name { get; }
}
这种行为的原因是什么?
VS 15.3.5,C# 7
【问题讨论】:
-
为什么它应该表现得不一样?你的期望是什么?
-
期望 - 相同的输出,相同的成员访问。我不明白为什么当基类已经实现的接口可以改变事情时,为什么将接口添加到类定义中。
-
你明白
public new string Name { get; }在Base上对Name做什么吗? -
嵌套类初始化很重要
-
在
IBase o = new Derived();中编译器有2个选择,它选择最佳匹配。
标签: c# inheritance interface