简体   繁体   English

隐藏.net中反射的私有字段

[英]Hiding a private field from reflection in .net

I have a class that performs some sensitive I/O operations across an entire disk volume. 我有一个类在整个磁盘卷上执行一些敏感的I / O操作。 By sensitive I mean if the operation goes wrong, it can potentially corrupt the target volume. 敏感我的意思是如果操作出错,它可能会破坏目标卷。

During some post-release testing, I found that the process can be corrupted using reflection to manipulate private fields. 在一些发布后测试期间,我发现使用反射操作私有字段可能会损坏进程。 The class is not sealed by design so that consumers of the library can create derivatives. 该类没有设计sealed ,因此图书馆的消费者可以创建衍生品。

Is there a way to secure private members to prevent modification via reflection (from derived or consumer code)? 有没有办法保护私人成员阻止通过反射进行修改(来自派生或消费者代码)?

UPDATE: I found a comment from Hans Passant to an old question mentioning [ReflectionPermission] . 更新:我找到了Hans Passant对一个提到[ReflectionPermission]老问题的评论。 Looking into that now. 现在调查一下。

There is no way to hide your field from Reflection. 没有办法从反射中隐藏你的领域。 It can be used to access and manipulate any field on a type. 它可用于访问和操作类型上的任何字段。 There are steps you can take like obfuscation which make it harder to identify fields and in turn harder to change via Reflection. 您可以采取一些步骤,如混淆,这使得识别字段变得更加困难,反过来更难以通过反射进行更改。 This is only a speed bump though. 这只是一个减速带。 A determined developer can use Reflection to beat any work arounds you have 一个坚定的开发人员可以使用Reflection来击败你所拥有的任何工作

Short Answer: No . 简答:

You cannot stop people from messing with your program if they have the privileges. 如果他们拥有特权,你就无法阻止他们搞乱你的程序。

I believe your best effort is going to be in obfuscating the code. 我相信你最大的努力就是混淆代码。 Otherwise, you cannot stop someone from using reflection to mar things up a bit. 否则,你无法阻止某人使用反射来破坏一些东西。

There is this post which may give you some idea on how you want to proceed. 这篇文章可能会让您对如何进行有所了解。

Private is just private to developers consuming your class. Private对于消费你的课程的开发者来说是私人的 You cannot prevent its access via reflection. 无法通过反射阻止其访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM