gpt4 book ai didi

c# - 继承 Class1 并实现 Interface1,以防 Class1 已经实现 Interface1

转载 作者:太空狗 更新时间:2023-10-29 21:49:21 25 4
gpt4 key购买 nike

第一件事。希望我的标题没有误导。我尽力表达它。

现在,请看下面的代码。案例 1 非常简单。这两种情况都按预期工作。我的问题是为什么编译器允许案例 2?是否有需要的特定场景。我想不出一个。

interface IEmployee
{
void Register(string role);
}

abstract class Employee : IEmployee
{
public void Register(string role)
{
Console.WriteLine(role);
}
}

// Case 1
class Manager : Employee
{
}

// Case 2
class Developer : Employee, IEmployee
{
}

class Test
{
public void Test1()
{
IEmployee emp1 = new Manager();
emp1.Register("manager"); // output "manager"

IEmployee emp2 = new Developer();
emp2.Register("developer"); // output "developer"
}
}

最佳答案

编辑

如我所料,答案可以在c#规范中找到

一些标语:

13.4.5 Interface implementation inheritance

Without explicitly re-implementing an interface, a derived class cannot in any way alter the interface mappings it inherits from its base classes

13.4.6 Interface re-implementation

A class that inherits an interface implementation is permitted to re-implement the interface by including it in the base class list

阅读更多以研究所有案例(可以在 Visual Studio 文件夹中找到数字副本)


首先想到:情况 2 是允许的,至少因为接口(interface)可以显式实现( sample)。它原来是可用选项的子集

public interface IEmployee
{
void Register(string role);
}

public abstract class Employee : IEmployee
{
public void Register(string role)
{
Console.WriteLine(role);
}
}

// Case 2
public class Developer : Employee, IEmployee
{
// this will not work without IEmployee in declaration!
void IEmployee.Register(string role)
{
Console.WriteLine("i'm developer!");
}
}
public class Program
{
public static void Main()
{
var dev = new Developer();
dev.Register("senior");

IEmployee e = dev;
e.Register("senior");
}
}

程序打印:

senior
i'm developer!

第一个值来自Employee.Register

第二个值 - 来自 Developer.Register


如果 Developer 定义为

// Case 2
public class Developer : Employee
{
public void Register(string role)
{
Console.WriteLine("i'm developer!");
}
}

同一个程序的输出是:

i'm developer!
senior

关于c# - 继承 Class1 并实现 Interface1,以防 Class1 已经实现 Interface1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33931793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com