简体   繁体   中英

Need multiple inheritance functionality in C#. What am I doing wrong?

class UDPClient
{
}

class LargeSimulator
{
}

class RemoteLargeSimulatorClient : UDPClient, LargeSimulator
{
}

The saying goes, if you need multiple inheritance, your design is off.

How would I get this done in C# without having to implement anything?

You can only inherent from a single base class in C#. However, you can implement as many Interfaces as you'd like. Combine this fact with the advent of Extension Methods and you have a (hacky) work-around.

C# only allows single inheritance, though you can inherit from as many interfaces as you wish.

You could pick just one class to inherit from, and make the rest interfaces, or just make them all interfaces.

You could also chain your inheritence like so:

class UDPClient
{
}

class LargeSimulator : UDPClient
{
}

class RemoteLargeSimulatorClient : LargeSimulator
{
}

To get multiple inheritance the way you want it, you need to make your UDPClient and LargeSimulator interface instead of class .

Class multiple inheritance isn't possible in C#

One possible substitute for multiple inheritance is mixins. Unfortunately C# doesn't have those either, but workarounds are possible. Most rely on the use of extension methods (as a previous answerer suggested). See the following links:

http://mortslikeus.blogspot.com/2008/01/emulating-mixins-with-c.html http://www.zorched.net/2008/01/03/implementing-mixins-with-c-extension-methods/ http://colinmackay.co.uk/blog/2008/02/24/mixins-in-c-30/

The short answer: Multiple inheritance is not allowed in C#. Read up on interfaces: http://msdn.microsoft.com/en-us/library/ms173156.aspx

The slightly longer answer: Maybe some other design pattern would suit you, like the strategy pattern, etc. Inheritance isn't the only way to achieve code reuse.

interface ILARGESimulator
{
}

interface IUDPClient
{
}

class UDPClient : IUDPClient
{
}

class LargeSimulator : ILARGESimulator
{
}

class RemoteLargeSimulatorClient : IUDPClient, ILargeSimulator
{
    private IUDPClient client = new UDPClient();
    private ILARGESimulator simulator = new LARGESimulator();

}

Unfortunately you will need to write wrapper methods to the members. Multiple inheritance in C# does not exist. You can however implement multiple interfaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM