Need multiple inheritance functionality in C#. Wha

2020-04-08 12:33发布

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?

6条回答
我只想做你的唯一
2楼-- · 2020-04-08 12:56
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.

查看更多
冷血范
3楼-- · 2020-04-08 13:06

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/

查看更多
霸刀☆藐视天下
4楼-- · 2020-04-08 13:10

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.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-04-08 13:18

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
{
}
查看更多
等我变得足够好
6楼-- · 2020-04-08 13:21

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#

查看更多
我命由我不由天
7楼-- · 2020-04-08 13:22

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.

查看更多
登录 后发表回答