我以前也问过类似的Question,但这一次有点扩展了。我已经问过的是在派生类中重写SomeProperty
,而这个类的答案是使用‘新’操作符。
但现在我又回到了同样的场景,
,这一次,我必须在基类中执行默认行为,同时在派生类中设置
SomeProperty
。
我必须强制从基类派生的用户在基类中执行一组代码,同时在派生类中设置SomeProperty
。我已经尝试了模板模式,但我需要将它绑定到我的Windows控件库中的自定义控件。所以我的基类不能是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 |
+------------------+
发布于 2012-03-02 17:28:03
如果我正确理解了您的问题,您可以使用base
关键字来确保原始方法也被执行。例如,
public new void Method()
{
DoMyCustomStuff();
base.Method();
}
https://stackoverflow.com/questions/9542444
复制相似问题