您什么时候会使用“受保护的内部”? 访问修饰符?
您可能已经知道,.NET Framework 的受保护的内部 访问修饰符以一种奇怪的方式工作:它并不意味着该类是受保护的 AND 内部,它表示该类是受保护 或 内部; 也就是说,可以从同一程序集中以及同一层次结构中访问修改后的类或成员。
那么,知道这一点:你什么时候会使用它? 你能给个例子吗? .NET 基类库中有一个很好的、启发性使用示例吗?
As you may already know, the .NET Framework's protected internal access modifier works in a strange way: It doesn't mean the class is protected AND internal, it says the class is protected OR internal; that is, the modified class or member can be accessed from whitin the same assembly as well as from the same hierarchy.
So, knowing this: When would you use it? Can you give an example? Is there a good, illuminating usage example inside .NET Base Class Library?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我很少需要使用这种访问修饰符组合,因为我认为除了最极端的情况之外,它都是设计不佳的指标。 但是,有时需要让类型转换器和编辑器等帮助器类访问程序集中的方法,但只允许派生类在其他用例中访问它。
一个示例可能是为类型转换器将类型转换为字符串的调用。
ToString()
通常不用于此目的,因此您可能希望类型转换器使用ToPersistableString()
调用,因此您将其设置为内部
。 然后,您决定从您的类派生的人们很可能希望使用此调用作为他们自己的派生类持久性方案的一部分,因此您也将其受保护
。.NET 框架使用
Control
上的AccessibilityNotifyClients
是内部受保护的
。 使用 Reflector,我可以看到这样做是为了CheckedItemCollectionCheckListBox
的 code> 可以在更改选中状态时访问它。I have rarely needed to use this access modifier combination as I think that in all but the most extreme circumstances, it's an indicator of poor design. However, sometimes it is necessary to have helper classes like type converters and editors access the method inside your assembly, but only allow derived classes to access it in other use cases.
An example might be a call that turns a type into a string for the type converter.
ToString()
generally isn't used for this purpose so you might have aToPersistableString()
call that you want your type converter to use, so you make itinternal
. Then you decide that people deriving from your class may well want to use this call as part of their own persistence scheme for their derived class so you make itprotected
as well..NET Framework Use
AccessibilityNotifyClients
onControl
isprotected internal
. Using Reflector, I can see that this was done so that theCheckedItemCollection
ofCheckListBox
could access it when changing checked states.我已将其用于内部方法,您希望能够在单独的名称空间中使用这些方法进行单元测试,单元测试名称空间包含该类的子类。 这允许访问受保护的方法。
也就是说,有一个论点是将所有内容公开以进行单元测试。
I've used it for internal methods that you wanted to be able to use in a separate name space for unit testing, the unit test name space contained a subclass of the class. which allowed the protected methods to be accessed.
That said there is an argument to make everything public for unit testing.
我想添加 ASP.Net MVC 框架的示例:
I would like to add an example from ASP.Net MVC framework: