为什么我得到"预期得到或设置访问者"这里?

时间:2016-07-24 23:09:32

标签: c# visual-studio oop

在下面的注释行中,为什么我会收到错误

  

期望获取或设置访问者

???

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SingleLinkedList
{

    class Program
    {
        static void Main(string[] args)
        {
        }
    }

    public class SingleLinkedList<T>
    {
        private class Node
        {
            T Val;
            Node Next;
        }

        private Node _root = null; 

        public T this[int index]
        {
            for(Node cur = _root; // error pointing to here
                index > 0 && cur != null; 
                --index, cur = cur.Next);

            if(cur == null)
                throw new IndexOutOfRangeException();

            return cur.Val;

        }

    }
}

1 个答案:

答案 0 :(得分:2)

您需要指定一个getter:

public T this[int index]
{
    get 
    {
        for(Node cur = _root;
            index > 0 && cur != null; 
            --index, cur = cur.Next);

        if(cur == null)
            throw new IndexOutOfRangeException();

        return cur.Val;
    }
}