How to handle a class you want to extend which is sealed in the .NET library?

前端 未结 7 1389
礼貌的吻别
礼貌的吻别 2021-01-02 02:54

I was reading somewhere about how to handle the issue of wanting to extend a sealed class in the .NET Framework library.

This is often a common and useful task to do

7条回答
  •  孤城傲影
    2021-01-02 03:22

    There is 'fake' inheritance. That is, you implement the base class and any interfaces the other class implements:

    // Given
    sealed class SealedClass : BaseClass, IDoSomething { }
    
    // Create
    class MyNewClass : BaseClass, IDoSomething { }
    

    You then have a private member, I usually call it _backing, thus:

    class MyNewClass : BaseClass, IDoSomething
    {
       SealedClass _backing = new SealedClass();
    }
    

    This obviously won't work for methods with signatures such as:

    void NoRefactoringPlease(SealedClass parameter) { }
    

    If the class you want to extend inherits from ContextBoundObject at some point, take a look at this article. The first half is COM, the second .Net. It explains how you can proxy methods.

    Other than that, I can't think of anything.

提交回复
热议问题