开发者

Change multiple inheritance into deriving from a template

Say I have a bunch of code for all controls, yet I need subclasses that interact with my software suite to use those common methods. I really want my subclass to derive from the control, not the class with the common code. (A MyEdit should derive from Edit, not from MyControl). Also, the suite interacts with controls using an interface which MyControl derives from. In order to do this in C++, I would use multi-inheritance like so

class MyEdit : public Edit, public MyControl;
class MyControl : public IControl;

However, I suddenly discover that I shouldn't use multi-inheritance if I want some 开发者_StackOverflowcontrols to be C# which doesn't support multi-inhertiance. So I thought I could do this...

class MyEdit : public MyControl<Edit>;
template class MyControl<Type> : public IControl;

Convert the common control stuff into a template, and give it the type of control I want to derive from.

However I'm not sure this will work, because the template templatizes Edit, but it doesn't necessarily create one does it? When I create the template will I actually be able to create the Edit?

And secondly, if this is possible, is it possible in C#? What would it look like?


I can't say I quite followed your question, but in regards to:

However I'm not sure this will work, because the template templatizes Edit, but it doesn't necessarily create one does it? When I create the template will I actually be able to create the Edit?

I would go for

template<class Controlled_t>
class MyControl : public Controlled_t, public IControl
{
 //My Control inherits from its templated class
}

so that MyControl<Edit> inherits Edit (which is created) and the interface


In C#, a class can only inherit from one other class, but it can implement multiple Interfaces, so if you want a class that can override behavior for more than one polymorphic type at runtime, you have to use Interfaces. The drawback of Interfaces is that they have no properties or base method implementations, so you may have to duplicate some of the methods in classes that implement the same Interface.

Another, C#-y way to get polymorphic runtime behavior is by attaching delegates. A lot of times I've found that what looks like a multiple-inheritance situation is better expressed as a multicast-delegate situation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜