C#-关于自定义集合与索引器

一、自定义集合定义 

1、通过继承IEnumerable, IEnumerator接口实现自定义集合;

2、需要实现IEnumerable.GetEnumerator()方法用来返回循环访问集合的枚举器,主要是迭代集合时使用;

3、实现IEnumerator接口的Current属性MoveNext()Reset()方法

Current属性:获取集合中当前位置的元素,

MoveNext():迭代集合中的下一个元素,

Reset():设置初始位置,位置位于集合第一个元素之前

二、自定义集合示例:

1、自定义集合:

    internal class JHStu : IEnumerable, IEnumerator
    {
        private Student[] students;
        public JHStu(Student[] stus)
        {
            students = new Student[stus.Length];
            for (int i = 0; i < stus.Length; i++)
            {
                students[i] = stus[i];
            }
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return (IEnumerator)this;
        }
        int position = -1;

        public object Current => students[position];
        public bool MoveNext()
        {
            position++;
            return position<students.Length;
        }

        public void Reset()
        {
            position = -1;
        }
    }

2、使用自定义集合: 

class Pro
{
    public static void Main()
    {
        Student[] stus = new Student[3] {
            new Student(1,"xiaoli"),
            new Student(2,"xiaohua"),
            new Student(3,"xiaohong")
        };
        JHStu stujh = new JHStu(stus);

        foreach (Student student in stus)
        {
            Console.WriteLine("{0}:{1}", student.Id, student.Name);
        }
        foreach (Student stu in stujh)
        {
            Console.WriteLine(stujh.Current);
        }
    }
}
internal class Student
{

    public int Id { get; set; }
    public string? Name { get; set; }
    public Student(int id, string name)
    {
        Id = id;
        Name = name;
    }
}

三、索引器的使用 

索引器的声明方式与属性相似,区别是索引器的声明需要以this定义参数

不能为静态static

声明格式:修饰符 类型 this[] 

                        {     

                                 get{ } 

                                 set{ }

                          }

示例代码

        public string this[int index]
        {
            get => students[index].Name;
            set => students[index].Name = value;

        }

使用

stujh[0] = "Auston";

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值