2

在 C# 或 VB.NET 等 OOP 语言中,如果我在超类中创建属性或方法,protected我将无法在我的表单中访问它们 - 它们只能在从该超类继承的类中访问。

要访问这些属性或方法,我需要创建它们public,这会破坏封装,或者将它们重新写入我的类,这会破坏继承。

这样做的正确方法是什么?

4

4 回答 4

2

如果您的代码需要要求类执行特定操作,但该类没有为您的代码提供执行此操作的方法,则该类不满足您的代码要求。

这有点像说我有一辆带有受保护方向盘的汽车(汽车),所以我无法访问它。车对我没用。

要么将这些成员设为公共(或至少在内部)并使用它们,要么放弃该类并使用一个为您的消费代码提供所需功能的类。

也许你真正要找的是一个界面。该接口包含您的代码所需的成员,并且您在类上实现该接口。这里的优点是您的类可以确定成员正在通过此接口而不是继承的子类访问。

于 2008-11-14T11:45:14.487 回答
1

“需要将它们公开,这会破坏封装”

不要将好的设计与讨厌的可见性规则混为一谈。可见性规则令人困惑。实际上有两种正交的可见性——子类和客户端。目前还不清楚为什么我们会从我们的子类中隐藏任何东西。但我们可以,用private.

这是重要的。封装并不意味着隐藏。受保护和私有不是良好封装的重要组成部分。您可以在所有内容都公开的情况下进行良好的设计(例如,Python 就是这样工作的)。

受保护/私有的东西——主要是——关于知识产权管理:你是否愿意(以具有法律约束力的“如果它不起作用”的方式)承诺界面?如果您的软件开发涉及律师,那么您会关心为您不承诺的事情添加保护和私有。

如果您不必与律师打交道,请考虑正确封装,但将所有内容公开。

于 2008-11-14T12:00:37.903 回答
0

抱歉,不清楚您所说的“在我的表格中”是什么意思-您的表格和您的两个班级之间的关系是什么?如果你的类是同一个项目中的控件,并且你想从表单中访问属性,你应该使用'internal'关键字。

于 2008-11-14T11:46:52.393 回答
0

至少有三种方法可以限制谁可以使用特定类实例的某些特定实例方法:

  1. Define the method as `protected`, `internal`, or `private`. In the first case, an instance method will only be usable from within derived-class methods of the same instance; in the second case, all classes within the assembly will have access to those methods, but classes outside won't; in the third case, no outside classes, even derived ones in the same assembly, will have access, unless their code is nested within the declaring class.
  2. Define the method as `public`, but have the classes that create instances keep them private and never expose them to the outside world. Anyone wanting to invoke an instance method on an object has to have an instance to invoke it on. If a class holds instances but never exposes direct references to them, the only instance methods that can ever be used on those instances will be those which the holding classes uses itself.
  3. Define the method as `public`, but have a constructor which accepts a location into which one or more delegates to private methods may be stored. Code with access to those delegates will be able to call the methods referred to thereby, but other code will not (except by using Reflection in ways which I think are only usable in full-trust scenarios).

If Reflection in non-full-trust scenarios would allow unbound delegates to be bound to arbitrary object instances, one could use nested classes to reinforce #3 so that one would have to access private fields to gain illegitimate access to the private functions; that would definitely be forbidden outside full-trust scenarios.

于 2012-04-24T16:20:43.640 回答