非公开成员为C#接口接口、成员

2023-09-02 21:26:09 作者:陌路〃荒年

在C#中,当你实现一个接口的所有成员默认为公用。你认为它的更好,如果我们可以指定访问修饰符(受保护的,内部的,除了私有当然)或更好的使用抽象类呢?

In C#, when you implement an interface all members are public by default. Do you think it's better if we can specify the accessibility modifier (protected, internal, except private of course) or better use an abstract class instead?

推荐答案

如果一个接口是内部的,它的所有成员都将是内部的组件。如果嵌套接口的保护,在外部类的只有子类可以访问该接口。

If an interface is internal, all its members will be internal to the assembly. If an nested interface is protected, only the subclasses of the outer class could access that interface.

内部成员的声明组件的外部连接的接口将是毫无意义的,因为将保护成员的声明外部类的外部连接的接口。

Internal members for an interface outside of its declaring assembly would be pointless, as would protected members for an interface outside of its declaring outer class.

接口的一点是描述一个合同接口的实现类型和用户之间。外部用户不会去关心和不应该的有无关心的实现,这是内部和保护成员的。

The point of an interface is to describe a contract between a implementing type and users of the interface. Outside callers aren't going to care and shouldn't have to care about implementation, which is what internal and protected members are for.

有关保护成员是由一个基类叫做抽象类的方式去指定的基类,并从他们继承的类之间的契约。但在这种情况下,实施的细节通常是非常相关的,除非它是一个堕落纯抽象类(其中的所有的成员是抽象的),在这种情况下,受保护的成员都是没用的。在这种情况下,去与接口并保存单个基类用于实现类型选择

For protected members that are called by a base class, abstract classes are the way to go for specifying a contract between base classes and classes that inherit from them. But in this case, implementation details are usually very relevant, unless it's a degenerate pure abstract class (where all members are abstract) in which case protected members are useless. In that case, go with an interface and save the single base class for implementing types to choose.

 
精彩推荐
图片推荐