开发者

C#: Calling a virtual method from constructor; advice?

开发者 https://www.devze.com 2022-12-11 17:42 出处:网络
In out program, we have the following class hierarchy: public class PagePanelBase: UserControl public sealed class CameraParameters: PagePanelBase

In out program, we have the following class hierarchy:

public class PagePanelBase: UserControl
public sealed class CameraParameters: PagePanelBase

CameraParameters overrides the BackColor property, setting the background color of some of the components it contains. If BackColor is set from the PagePanelBase constructor (InitializeComponent called from th开发者_Go百科ere), the CameraParameters constructor hasn't been called yet, so we get a null pointer dereference -- the standard "don't call virtual methods from the constructor" problem.

Now how can we solve this issue? We NEED to use this hierarchy, and we NEED to set the background color from the base class. At present, each deriving class uses a boolean variable "isInitialized" that is set in InitializeComponent, and every overridden method calls InitializeComponent if necessary before doing anything. Is there a better way of doing this? There are already enough broken windows in the code...


Can you set the background color in an event handler, e.g. OnLoad?


Have you tried an abstract method rather than a virtual? Unfortunately, it make not work in your overall hierarchy, but it's worth considering.

0

精彩评论

暂无评论...
验证码 换一张
取 消