将变量声明为“私有”是否有效?在C#中保护Windows中的内存不被内存扫描器访问?
我的同事总是告诉我,如果我们将任何内容声明为“公共”,那么这是危险的,因为任何程序都可以访问该内存,而解决方案是使用“私有”访问修饰符。
我想知道这是否属实。
My workmate always tells me that if we declare anything as "public" then it is dangerous because then any program can access that memory and that the solution is to use the "private" access modifier.
I am wondering if this is infact true.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
事实上,这不是。
访问修饰符仅用于帮助组织代码。它们只是在某种意义上保护它,即您将玻璃放在猫够不到的地方,以防止玻璃被打翻。
That is not, in fact, true.
Access modifiers are only there to help organize your code. They only protect it in the sense that you protect your glass from being knocked over by setting it out of reach of the cat.
public
和private
访问修饰符仅与这些结构(类、方法或变量)对同一应用程序中其他类的可见性有关。进程和用户之间的内存保护由操作系统强制执行。就Windows而言,它确实确保非管理员级别(和系统环)进程/线程无权访问未以开放权限显式共享的内存(例如共享内存)。实际上,Windows 允许进程向特定的内存区域授予非常特定的权限,但 C# 的语言定义中并未提供这一点。您需要访问系统 API 来控制对特定内存块的访问权限;默认情况下,所有内存块都受操作系统保护。现在,如果内存扫描器在ring-0 中运行或具有特定的提升权限,则您在进程中无法执行任何操作来阻止该访问。
public
andprivate
access modifiers only have to do with the visibility of those structures (classes, method, or variables) to other classes within the same application. Memory protection between processes and users is enforced by the operating system. In the case of Windows, it does ensure that non-administrator level (and system ring) processes/threads do not have access to memory that is not explicitly shared (such as shared memory) with open permissions. Actually, Windows allows processes to grant very specific rights to specific areas of memory, but this is not provided in the language definition of C#. You would need to access system APIs to control grant that kinds of access to specific blocks of memory; by default all blocks of memory are protected by the OS.Now, if the memory scanner is running in ring-0 or with specific elevated privileges there is nothing you can do in your process to block that access.
C# 修饰符对内存寻址能力没有影响——处理器和操作系统架构控制这一点。
C# modifiers have no influence over memory adressability - the processor and OS architecture control that.