如何延长两个类以同样的方式,而不复制和粘贴?而不、两个、方式

2023-09-03 23:32:35 作者:迷人三句诗

我写了一个自绘的TabControl ,但我们的项目还使用了 TabWorkspace 这源于的TabControl 。目前,我有

I've written an owner-drawn TabControl, but our project also uses TabWorkspace which derives from TabControl. At the moment, I've got

public class OurTabControl : TabControl
{
     // some code that overrides protected methods
}

public class OurTabWorkspace : TabWorkspace
{
    // the same code
}

我想只有共享code出现在一个地方,这样我们就不必维护两个副本。这是可能在C#中,如果是的话,怎么办?

I'd like to only have the shared code appear in one place, so we don't have to maintain two copies. Is this possible in C#, and if so, how?

推荐答案

您可以使用一个接口和编写扩展方法它做什么。

You could do it using an interface and writing an extension method.

class OurTabControl: IBehavior
class OurTabWorkspace: IBehavior

interface IBehavior
{    
}

static class BehaviorExtensions
{
   static [returntype] RepeatedBehavior(this IBehavior behavior)
   {
       //repeated code here
   } 
}