简体   繁体   中英

Controlling access to child controls on base class?

Let me preface this question by stating that i don't usually condone the practice of applying inheritance principles to user-interface design; that is, developing an application-specific Form or UserControl with a number of child controls, and extending this in subclasses which add controls or alter the layout of those on the base class. It sometimes seems like an elegant design solution, but it rarely works out that way...

With that in mind, I have a question concerning controlling access to child controls in the above scenario; Is there a secure way to prevent a subclass from accessing/modifying child controls on the base class?

I know that the principle way of achieving this is to use the (default) private access modifier when declaring the member variables for child controls; however, this does not stop a subclass from accessing a control on its base class like so:

base.Controls["someControl"].Text = "Look, I vandalised your control";

Obfuscating the names of the controls achieves little, and attempting to hide the Controls property using new doesn't solve the problem either (since the subclass can cast its base type back to Control and access the property that way). Note that this problem also applies when accessing the control from outside of the scope of the class - all you need is a reference to the control/form and then you can go about modifying child controls to your heart's content.

So, what techniques would you recommend for protecting (certain) child controls from being manipulated in this manner?

Anything beyond private would seem over the top. Next to the Controls property there always is Reflection too.

The access modifier private is not about security, it is an organizational tool. Consider it a knee-high fence.

So your best solution would be to talk to your programmers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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