gpt4 book ai didi

c# - 为什么可以在基类中实现接口(interface)方法?

转载 作者:IT王子 更新时间:2023-10-29 03:45:45 27 4
gpt4 key购买 nike

<分区>

在我的项目中,我发现了一种在 C# 中似乎完全有效的奇怪情况,因为我没有编译时错误。

简化的例子看起来像这样:

using System;
using System.Collections.Generic;

namespace Test
{

interface IFoo
{
void FooMethod();
}

class A
{
public void FooMethod()
{
Console.WriteLine("implementation");
}
}

class B : A, IFoo
{
}

class Program
{
static void Main(string[] args)
{
IFoo foo = new B();
foo.FooMethod();
}
}
}

这样的代码可以编译。但是,请注意 A 不是 IFoo 并且 B 没有实现 IFoo 方法。就我而言,偶然(重构后),A 具有具有相同签名的方法。但是为什么A要知道如何实现IFoo接口(interface)的FooMethod呢? A 甚至不知道 IFoo 的存在。

对我来说,这样的设计很危险。因为每次我实现某个接口(interface)时,我都应该检查这个接口(interface)中的每个方法是否“干扰”了基类方法。

如果这是“纯 C# 功能”?这叫什么?我错过了什么吗?

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