C #: simple replacement with multiple / mixin inheritance?

I have a class from an external library that I need to extend into the antoher class. In addition, extensions must remain reusable, as I need them in other places.

Since neither mixins nor multiple inheritance are supported in C #, what is the general way to solve this problem?

namespace ExtLib
{
    public class Properties
    {
        public virtual int fieldN { get; set; }
    }
}

namespace MyLib
{
    public class Extensions
    {
        public virtual int fieldM { get; set; }
    }
}

namespace MyProject
{
    public class MyModel
    {
        // needs to have all fields from ExtLib.Properties AND MyLib.Extensions
    }

    public class MyOtherModel
    {
        // needs to have all fields from MyLib.Extensions,
        // MyLib.Extensions should be reusable
    }
}

I know that a decision can be an interface IExtensions, but it leads to a lot of duplication, because the number of fields Extensionsand Propertiespretty large (and they vary greatly in the development phase).


Are there any recommendations?

+4
source share
2 answers

How about you just merging instances of these classes into MyModel?

public class MyModel
{
    private Properties _properties;
    private Extensions _ extensions;

    public MyModel(Properties properties, Extensions extensions)
    {
        _properties = properties;
        _extensions = extensions;
    }

    public Properties Prop
    {
        get { return _properties; }
    }

    public Extensions Ext
    {
        get { return _extensions; }
    }
}

, , getter private setter.

Properties Extensions MyModel. - - , , .

, , , , .

+6

, ExtLib, MyProject

namespace ExtLib
{
    public class Properties
    {
        public virtual int fieldN1 { get; set; }
        public virtual int fieldN2 { get; set; }
        public virtual int fieldN3 { get; set; }
        public virtual int fieldN4 { get; set; }
        public virtual int fieldN5 { get; set; }
    }
}

namespace MyLib
{
    abstract class Extensions : Properties
    {
        public virtual int fieldM1 { get; set; }
        public virtual int fieldM2 { get; set; }
        public virtual int fieldM3 { get; set; }
        public virtual int fieldM4 { get; set; }
        public virtual int fieldM5 { get; set; }
    }
}

namespace MyProject
{
    public class MyModel : Extensions
    {
        // contains all fields from ExtLib.Properties AND MyLib.Extensions
    }
}
0

Source: https://habr.com/ru/post/1610492/


All Articles