开发者

How to extend a user control without calling base code

Language: C# Topic: Extending Controls.

I have a user control, B, which has a field, F, which is a control for displaying images.

I have a second user control, X, which extends B. It utilises the base F but has it's own implementation (displays buttons etc specific to X).

Both X and B are found in separate projects and B is not abstract; it is a concrete implementation.

The Problem: When X is created, first B's contrstructor is called wherein it initialize F. After calling B's constructor is then executes it's own constructor wherein it sets F to something else.

This is not desireable:

1) two instances of F exists and while X should be using the new F it seems to reference the base F when it comes to displaying the images.

Workarounds:

1) In X, before replacing F I can dispose of base.F - or

2) In B, I can test the class type: if type is X then skip F's ini开发者_如何学编程tialization.

While I can use either of these workarounds, something tells me that a better architecture exists. But what?


Try lazy initialization:

public class B
{
    private F f;

    public F F
    {
        get { return f ?? (f = InitializeF()); }
        set { f = value; }
    }

    protected virtual F InitializeF()
    {
        return new F();
    }
}

public class X : B
{
    protected override F InitializeF()
    {
        return new SomeOtherF();
    }
}


Would it make sense to derive both B and X from a common base, rather than deriving X from B? If you find yourself saying "I want to prevent the base class from doing something", then maybe it shouldn't derive from that class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜