0

例如,这两种方法都需要更新count变量:

        public void AddFront(T data) {
            Node<T> newNode = new Node<T>(data, null, null); 
            if (count == 0) {
                head = tail = newNode;
            }
            else {
                newNode.Next = head;
                head.Previous = newNode;
                head = newNode;
            }
            // don't forget
            count++;
        }

        public void AddBack(T data) {
            Node<T> newNode = new Node<T>(data, null, null);
            if (count == 0) {
                head = tail = newNode;
            }
            else {
                newNode.Previous = tail;
                tail.Next = newNode;
                tail = newNode;
            }
            // don't forget
            count++;
        }

我想知道是否有一个属性可以强制发生operation这样的事情?否则它会触发编译时错误消息。

4

1 回答 1

2

一个属性,没有。(虽然我会阅读@Michael建议的代码合同)

但是,您可以重构您的代码。有相当多的共性。也许创建一个单独的方法,该方法接受作为附加参数是否添加到头部或尾部。类似(未经测试):

    private void Add(T data, bool front) {
        Node<T> newNode = new Node<T>(data, null, null);
        if (count == 0) {
            head = tail = newNode;
        }
        else if (front) {
            newNode.Next = head;
            head.Previous = newNode;
            head = newNode;
        else {
            newNode.Previous = tail;
            tail.Next = newNode;
            tail = newNode;
        }
        // don't forget
        count++;
    }

    public void AddFront(T data) {
        Add(data, true);
    }

    public void AddBack(T data) {
        Add(data, false);
    }
于 2012-07-25T22:15:29.503 回答