How to do multiple inheritances?

G

Guest

Hi,

I think the derived class in C# can inherit from only one class. So, if I need multiple inheritances, I will need to have interfaces. However, interfaces doesn't have the implementation of methods. Suppose, if I want to have a derived class inherit the actual methods from 3 different base classes, how can I do that?

Thanks.
 
J

Justin Rogers

Encapsulation is the only manner you can do this with, and that gets complicated
with three
classes. What you might do here is use some reflection utilities that generate
method thunks
on your class that then map internally to copies of the three other classes you
hold instances
to. Of course the plumbing of making sure your local variables are used,
initializing those 3
different classes, etc... are all up to you.

I've done some similiar items with creating a Regex string class. Obviously
Regex and String
are both separate classes and so I had to aggregate the methods together.


--
Justin Rogers
DigiTec Web Consultants, LLC.

ligth_wt said:
Hi,

I think the derived class in C# can inherit from only one class. So, if I
need multiple inheritances, I will need to have interfaces. However, interfaces
doesn't have the implementation of methods. Suppose, if I want to have a
derived class inherit the actual methods from 3 different base classes, how can
I do that?
 
G

Guest

Thanks for your hints. What you've said is a bit out out of my head. Is there a place to find a good example? Thanks.
 
N

Nick

Multiple Inheritance, like you have mentioned, isnt supported. To achive
what you wish, the more advanced mechanism to assume is that of delegation.
Out of the three classes you wish to inherit functionality, choose the best
abstraction for the root. Try using the is-a test to make sure you get the
most appropriate class. On this class, realize the two other interfaces
(roles) by implementing them on the class:

public class A : IRoleB, IRoleC
{
private IRoleB _iRoleB;
private IRoleC _iRoleC;

public A(IRoleB roleBImplementation, IRoleC roleCImplementation)
{
_iRoleB = roleBImplementation;
_iRoleC = roleCImplementation;
}

// IRoleB methods
....

// IRoleC methods
...
}

In many cases, multiple inheritance of three classes (or even two) can
typically be broken down into the design above, which is much more flexible,
and open and closed.

HTH

Nick.


ligth_wt said:
Hi,

I think the derived class in C# can inherit from only one class. So, if I
need multiple inheritances, I will need to have interfaces. However,
interfaces doesn't have the implementation of methods. Suppose, if I want
to have a derived class inherit the actual methods from 3 different base
classes, how can I do that?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top