需要关于接口隔离原则的建议

时间:2021-07-09 07:53:48

标签: c#

我试图从父抽象类中分离出一些属性,这些属性在所有子类中并不常见。

但是我的父母正在从它的一个属性的 setter 访问一些不常见的抽象方法。这种情况阻碍了我使用 ISP。

public abstract class Parent
    {
        public abstract string MyProperty1 { get; set; }
        public abstract string MyProperty2 { get; set; }
        public abstract void Test();

        //Non abstract property
        public string MyProperty3
        {
            get { return ""; }

            set { Test(); }
        }
    }

    //Now Kid1 and Kid2 absolutely need all the parent components. So let see the Kid3 now...
    //Kid3 will not in need of all the parent components.
    public class Kid3 : Parent
    {
        public override string MyProperty1
        {
            get
            {
                return "";
            }

            set
            {
                /*Do something*/
            }
        }

        // this is not needed for Kid3 but forced to implement
        public override string MyProperty2
        {
            get
            {
                throw new NotImplementedException();
            }

            set
            {
                throw new NotImplementedException();
            }
        }

        // this is not needed for Kid3 but forced to implement
        public override void Test()
        {
            throw new NotImplementedException();
        }
    }

因此,我从父级中删除了 Myproperty2 和 Test() 方法,并移至如下界面。

public interface ICommonMembers
{
    string MyProperty2 { get; set; }
    void TestMethod();
}

public class Kid1 : Parent, ICommonMembers { }
public class Kid2 : Parent, ICommonMembers { }
public class Kid3 : Parent { }

问题来了 由于我从 Parent 类中删除了 Test(),Myproperty3 的 setter 给了我一个错误。

0 个答案:

没有答案
相关问题