【发布时间】:2012-03-03 09:40:09
【问题描述】:
我之前问过类似的Question,但这次它有点扩展。我已经问过的是在派生类中覆盖SomeProperty,答案是使用'new'运算符。
但现在我又回到了同样的场景中,但是,
这一次我必须在基类中执行一个默认行为 同时在派生类中设置
SomeProperty。
我必须强制从我的基类派生的用户在基类中执行一组代码,同时在派生类中设置SomeProperty。我已经尝试过使用模板模式,但我需要将它绑定到我的 Windows Phone 控件库中的自定义控件。所以我的基类不能是abstract 类。因此,我无法在基类中指定通用功能,并确保在派生类中设置变量时强制执行该功能。
在派生类中设置属性时,是否有任何其他方法可以强制在基类中执行此代码(或某种规则)?
编辑: 我还应该提到,从基类派生的人不应该调用基类中的特定行为。我需要强制调用。
+---------------+
| UIElement |
|---------------| +----------------------+
| ... | | My Windows Application
| SomePropert{} | |----------------------|
| //Force to |<---+ |+--------------------+|
| //to xcute this code ||MyUserControl ||
+---------------+ | ||--------------------||
+--------------+-----+ || ||
|FrameWorkElement | |+--------------------+|
|--------------------| |//Want to use |
| ... |<-+ |// SomeProperty; |
+--------------------+ | | |
+-----------+-+ | |
|Control | | |
|-------------| +----------------------+
| ... |<---+
+-------------+ |
+-----------+---+
| UserControl |
|---------------|<---+
| ... | |
+---------------+ |
+----------+-------+
| MyUserControl |
|------------------|
| SomeProperty{} |
| //Want to override
| //Setting this here|
|//should make sure|
|//base class code |
|//gets executed |
+------------------+
【问题讨论】:
-
您可以在方法上使用
new,就像在属性上一样。您还可以使用一些反射来到达基类内部并戳成员。我的建议是使用反射和缓存代理。
标签: c# windows-phone-7 inheritance overriding