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

后端 未结 6 1891
野性不改
野性不改 2021-01-19 09:08
class UDPClient
{
}

class LargeSimulator
{
}

class RemoteLargeSimulatorClient : UDPClient, LargeSimulator
{
}

The saying goes, if you need multip

相关标签:
6条回答
  • 2021-01-19 09:11

    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.

    0 讨论(0)
  • 2021-01-19 09:19

    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.

    0 讨论(0)
  • 2021-01-19 09:19

    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/

    0 讨论(0)
  • 2021-01-19 09:28
    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.

    0 讨论(0)
  • 2021-01-19 09:35

    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
    {
    }
    
    0 讨论(0)
  • 2021-01-19 09:36

    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#

    0 讨论(0)
提交回复
热议问题