界面及其可访问性

发布于 2024-10-15 07:56:03 字数 763 浏览 1 评论 0原文

我在面试中被问到一个关于接口的问题。我不确定这是否真的可能。请看下面的问题。

有 3 个接口 ABCA 继承自接口 BC

public interface A : B,C
{

} 

我们必须确保该接口的用户不能使用 B > 和 C 直接或独立,并且必须仅使用 A

我可以想到以下场景:

  1. 制作 BC 内部接口。但我没有看到任何实际用途,因为我可以直接定义 A 本身的所有成员。
  2. BC 设为私有接口。但我怎样才能做到呢?另外,我在下面的 MSDN 链接中看到 BC 必须至少与 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:

  1. Make B and C inner interfaces. But I don't see any real use as I could directly define all the members in A itself.
  2. Make B and C private interfaces. But how can I make it? Also, I have seen at the below MSDN link that B and C 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

遗心遗梦遗幸福 2024-10-22 07:56:03

您所要求的将违反里氏替换原则

如果 A 以这种方式实现 B,它应该始终可以直接用作 B。试图阻止这种情况将违反面向对象设计的主要规则之一。

我怀疑面试官是想看看你是否理解这个核心概念,并且从一开始就会说“这是错误的,因为……”。

What you are asking for would be a violation of the Liskov Substitution Principle.

If A implements B this way, it should always be usable directly as a B. 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.

口干舌燥 2024-10-22 07:56:03

在我看来,这从一开始就是一个糟糕的设计模式。如果用户需要继承 BC,正如您所说,那么只创建一个接口更有意义。其次,BC 必须至少与 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 and C, as you said, it make more sense to just create the one interface. Secondly, B and C 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.

小红帽 2024-10-22 07:56:03

我们必须确保用户
该接口不能使用B和C
直接或独立地并且必须
只使用A。

你不需要掩盖B或C来强迫别人只使用A,无论你在哪里使用B或C并且想等待只A,请将其更改为A。

希望它有帮助!

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.

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文