C# 接口的非公共成员 [英] Non Public Members for C# Interfaces

查看:37
本文介绍了C# 接口的非公共成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,当您实现一个接口时,所有成员都是隐式公开的.如果我们可以指定可访问性修饰符(protectedinternal,当然除了private),或者我们应该只使用一个抽象类?

In C#, when you implement an interface, all members are implicitly public. Wouldn't it be better if we could specify the accessibility modifier (protected, internal, except private of course), or should we just use an abstract class instead?

推荐答案

如果接口是内部的,则其所有成员都将是程序集的内部.如果嵌套接口受保护,则只有外部类的子类可以访问该接口.

If an interface is internal, all its members will be internal to the assembly. If a 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.

这篇关于C# 接口的非公共成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆