oop - 接受两个接口中函数的名称冲突
问题描述
这是语言不可知论的,因为我的问题适用于任何具有该interface
概念的语言。(或快速协议)
在 C# 中考虑这个程序:
interface Inter1
{
int Count();
}
interface Inter2
{
int Count();
}
public class SomeClass : Inter1, Inter2
{
public int Count() // which one is it ?
{
return 0;
}
}
static void Main(string[] args)
{
Inter1 c = new SomeClass();
int i = c.Count();
}
或在 C++ 中: https ://godbolt.org/z/dFLpji
我很难理解为什么这是可以容忍的,尽管看起来所有可能的符号引用都是明确的,因为静态类型将指定我们正在谈论的函数。
但是,隐藏姓名不是很危险吗?
我正在考虑的问题的说明:
// in FileA.cs on day 0
interface DatabaseCleaner
{
void Execute();
}
// in FileFarAway.cs day 140
interface FragmentationLogger
{
void Execute(); // unfortunate naming collision not noticed
}
// in PostGreAgent.cs day 141
public class PostGreAgent : DatabaseCleaner, FragmentationLogger
{
public void Execute()
{ // I forgot about the method for database cleanup, or dismissed it mentally for later. first let's test this
allocator.DumpFragmentationInfo();
}
private Allocator allocator;
}
// client.cs
AgentsManager agents;
void Main(string[] args)
{
var pa = new PostGreAgent();
agents.Add(pa);
// ... later in a different location
DatabaseCleaner cleaner = agents.FindBest();
cleaner.Execute(); // uh oh
}
解决方案
这里没有歧义。
接口/协议只是一个需求列表,说明实现/符合它的对象必须能够做什么。Inter1
并且Inter2
都说无论谁实现它都必须能够Count()
。因此,如果可以Count()
,您可以实现这两个接口。就这么简单。这里没有歧义,因为只有一种. 并且是一回事。Count
Inter1.Count
Inter2.Count
请注意,在 C# 中,您可以显式实现接口,本质上提供了Count
forInter1
和的不同实现Inter2
。行为是非显式实现将隐藏显式实现,因此您只能使用接口的编译时类型访问显式实现。
推荐阅读
- laravel - Laravel Livewire:访问和操作哈希 URI
- java - 在 Java Cup 中的状态中发现 Shift/Reduce 冲突
- angular - 自定义角度表单组件中的触发更改事件
- c++ - 打印要选择的两个元素的功率总和
- reactjs - react-quilljs 和 reactjs-popup 不能一起工作
- javascript - Javascript没有验证是否输入了特殊字符
- reactjs - 为什么导入特定组件会导致捆绑包中的整个库?
- node.js - 从 Postgres Sql 中检索数据并在日期选择器中显示
- docker - 如何运行 nginx docker 底层 docker-entrypoint.sh
- c# - ASP.NET Core Controller 返回的 ViewResult 消耗在哪里?