界面及其可访问性
我在面试中被问到一个关于接口的问题。我不确定这是否真的可能。请看下面的问题。
有 3 个接口 A
、B
和 C
。 A
继承自接口 B
和 C
:
public interface A : B,C
{
}
我们必须确保该接口的用户不能使用 B
> 和 C
直接或独立,并且必须仅使用 A
。
我可以想到以下场景:
- 制作
B
和C
内部接口。但我没有看到任何实际用途,因为我可以直接定义A
本身的所有成员。 - 将
B
和C
设为私有接口。但我怎样才能做到呢?另外,我在下面的 MSDN 链接中看到B
和C
必须至少与 A 一样可访问:http://msdn.microsoft.com/en-us/library/aa664578%28v=VS.71 %29.aspx。
有什么办法可以做到这一点还是问题本身是错误的?
I have been asked a question in an interview about interfaces. I am not sure whether it's really possible. Please see the question below.
There are 3 interfaces A
, B
, and C
. A
inherits from interfaces B
and C
:
public interface A : B,C
{
}
We have to make sure that users of this interfaces can't use B
and C
directly or independently and have to use only A
.
I could think of the following scenarios:
- Make
B
andC
inner interfaces. But I don't see any real use as I could directly define all the members inA
itself. - Make
B
andC
private interfaces. But how can I make it? Also, I have seen at the below MSDN link thatB
andC
have to be at least as accessible as A: http://msdn.microsoft.com/en-us/library/aa664578%28v=VS.71%29.aspx.
Is there any way to do this or is the question itself wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您所要求的将违反里氏替换原则。
如果
A
以这种方式实现B
,它应该始终可以直接用作B
。试图阻止这种情况将违反面向对象设计的主要规则之一。我怀疑面试官是想看看你是否理解这个核心概念,并且从一开始就会说“这是错误的,因为……”。
What you are asking for would be a violation of the Liskov Substitution Principle.
If
A
implementsB
this way, it should always be usable directly as aB
. Trying to prevent this would be violating one of the main precepts of object oriented design.I suspect the interviewer was trying to see if you understood this core concept, and would say "This is wrong because ..." right from the start.
在我看来,这从一开始就是一个糟糕的设计模式。如果用户需要继承
B
和C
,正如您所说,那么只创建一个接口更有意义。其次,B
和C
必须至少与 A 一样可访问。(如果 A 是公共的,则不能将它们设置为内部或私有)。我认为唯一真正的解决方案是将接口定义合并到A中,而不是分别拥有这三个。
Seems to me like that's a bad design pattern from the get-go. If users are required to inherit both
B
andC
, as you said, it make more sense to just create the one interface. Secondly,B
andC
must be at least as accessible as A. (You can't make them internal or private if A is public).I think the only real solution is to combine the interface definitions into A, rather than having the three seperately.
你不需要掩盖B或C来强迫别人只使用A,无论你在哪里使用B或C并且想等待只A,请将其更改为A。
希望它有帮助!
You don't need to obscure B or C to force someone to use just A, wherever you are using B or C and want to wait just A, please change it to A.
hope it helps!