C# 类内部添加索引器

 

    public class PersonTable : Indexer
    {
        public int xuhao { get; set; }
        public string name { get; set; }
        public string tel { get; set; }

        string Indexer.this[int index]
        {
            get
            {
                if (index == 0) return xuhao.ToString();
                else if (index == 1) return name;
                else if (index == 2) return tel;
                else return null;
            }
            set
            {
                if (index == 0) xuhao = Convert.ToInt32(value);
                else if (index == 1) name = value;
                else if (index == 2) tel = value;
            }
        }

        int Indexer.this[string propname]
        {
            get
            {
                if (propname == "xuhao") return 0;
                else if (propname == "name") return 1;
                else if (propname == "tel") return 2;
                else return -1;
            }
        }
    }
    public interface Indexer
    {
        //定义索引器
        string this[int index] { get; set; }
        //获取索引,传入值必须为tolower
        int this[string propname] { get; }
    }

 

posted @ 2017-10-31 13:19  听雨的人  阅读(928)  评论(0编辑  收藏  举报