天天看點

090923 T 一個對象一對多關聯的問題

程式設計時遇到對象關聯api的設計問題,感覺可能這種api的設計方案本身就有問題,是以目前還未有解決方案。

問題如下:

using system;

using system.collections.generic;

using system.linq;

using system.text;

namespace consoleapplication

{

    /// <summary>

    /// 在notimplement的方法/屬性中填入相應内容,以保證程式不會抛出異常。

    /// (就是:parent屬性,addchild方法,removechild方法。)

    /// 

    /// 不能修改其它代碼。

    /// </summary>

    class program

    {

        static void main(string[] args)

        {

            parent parenta = new parent();

            parent parentb = new parent();

            child child = new child();

            parenta.addchild(child);

            child.parent = parentb;

            assert(parenta.children.count == 0, parentb.children.count == 1, child.parent == parentb);

            assert(parentb.children.count == 0, parenta.children.count == 1, child.parent == parenta);

            child.parent = null;

            assert(parentb.children.count == 0, parenta.children.count == 0, child.parent == null);

        }

        static void assert(params bool[] values)

            foreach (var value in values)

            {

                if (value == false)

                {

                    throw new exception();

                }

            }

    }

    class parent

        private list<child> _children;

        public parent()

            this._children = new list<child>();

        public ilist<child> children

            get

                return new system.collections.objectmodel.readonlycollection<child>(this._children);

        public void addchild(child child)

            throw new notimplementedexception();

        public void removechild(child child)

    class child

        private parent _parent;

        public parent parent

                throw new notimplementedexception();

            set

}

繼續閱讀