What are some good alternatives to multiple-inheritance in .NET?

后端 未结 6 1433
梦如初夏
梦如初夏 2020-12-13 13:49

I\'ve run into a bit of a problem with my class hierarchy, in a WPF application. It\'s one of those issues where you have two inheritance trees merging together, and you can

6条回答
  •  心在旅途
    2020-12-13 14:30

    I think is a one of solution.

    public interface IClassA
    {
        void Foo1();
        void Foo2();
    }
    
    public interface IClassB
    {
        void Foo3();
        void Foo4();
    }
    
    public class ClassA :IClassA
    {
        #region IClassA Members
    
        public void Foo1()
        {
        }
    
        public void Foo2()
        {
        }
    
        #endregion
    }
    
    public class ClassB :IClassB
    {
        #region IClassB Members
    
        public void Foo3()
        {
        }
    
        public void Foo4()
        {
        }
    
        #endregion
    }
    
    public class MultipleInheritance :IClassA, IClassB
    {
        private IClassA _classA;
        private IClassB _classB;
    
        public MultipleInheritance(IClassA classA, IClassB classB)
        {
            _classA = classA;
            _classB = classB;
        }
    
        public void Foo1()
        {
            _classA.Foo1();
        }
    
        public void Foo2()
        {
            _classA.Foo2();
            AddedBehavior1();
        }
    
        public void Foo3()
        {
            _classB.Foo3();
            AddedBehavior2();
        }
    
        public void Foo4()
        {
            _classB.Foo4();
        }
    
        private void AddedBehavior1()
        {
    
        }
    
        private void AddedBehavior2()
        {
    
        }
    }
    

    Class MultipleInheritance add new behavior to two different object without affecting the behavior of this objects. MultipleInheritance have the same behaviors as delivered objects (Inherits both behaviors).

提交回复
热议问题