“内部"的实际用途C#中的关键字 [英] Practical uses for the "internal" keyword in C#

查看:23
本文介绍了“内部"的实际用途C#中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请您解释一下 C# 中 internal 关键字的实际用法?

Could you please explain what the practical usage is for the internal keyword in C#?

我知道 internal 修饰符限制了对当前程序集的访问,但是我应该在什么时候以及在什么情况下使用它?

I know that the internal modifier limits access to the current assembly, but when and in which circumstance should I use it?

推荐答案

您希望从同一程序集中的许多其他类访问的实用程序或帮助程序类/方法,但您希望确保其他程序集中的代码可以'访问.

Utility or helper classes/methods that you would like to access from many other classes within the same assembly, but that you want to ensure code in other assemblies can't access.

来自 MSDN(通过archive.org):

From MSDN (via archive.org):

内部访问的一个常见用途是在基于组件的开发中,因为它使一组组件能够以私有方式协作,而不会暴露给应用程序的其余部分代码.例如,用于构建图形用户界面的框架可以提供使用具有内部访问权限的成员进行协作的 Control 和 Form 类.由于这些成员是内部成员,因此不会向使用该框架的代码公开.

A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.

您还可以将内部修饰符与 InternalsVisibleTo 程序集级别属性,用于创建被授予对目标程序集内部类的特殊访问权限的朋友"程序集.

You can also use the internal modifier along with the InternalsVisibleTo assembly level attribute to create "friend" assemblies that are granted special access to the target assembly internal classes.

这对于创建单元测试程序集很有用,然后允许调用要测试的程序集的内部成员.当然,没有其他程序集被授予这种级别的访问权限,因此当您发布系统时,会保持封装.

This can be useful for creation of unit testing assemblies that are then allowed to call internal members of the assembly to be tested. Of course no other assemblies are granted this level of access, so when you release your system, encapsulation is maintained.

这篇关于“内部"的实际用途C#中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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