C#索引器与数组的区别

1.索引器的索引值类型不限定为整数

2.索引器允许重载

3.索引器不是一个变量

4.索引器以函数签名方式this标识,而属性采用名称来标识,名称可以任意

5.索引器不能使用static来进行声明,属性可以。索引器永远属于实例成员,因此不能声明为static。

using System;
using System.Collections.Generic;

namespace 编码练习
{
    public class Student {
        public string  Name { get;set;}
        public int CourseID { get; set; }
        public int Score { get; set; }

    }
    public class FindScore
    {
        private List<Student> student { get; set; }
        public FindScore()
        {
            student = new List<Student>();
        }
        public int this[string name,int courseid] {
            get {
                var s = student.Find(x=>x.Name== name&&x.CourseID==courseid);
                if (s!=null)
                {
                    return s.Score;
                }
                return -1;
            }
            set {
                student.Add(new Student() {Name=name,CourseID=courseid,Score=value });
            }
        }
        //搜索
        public List<Student> this[string name]
        {
            get
            {
                List<Student> liststudents = student.FindAll(x => x.Name == name);
                return liststudents;
            }
        }

        public static void Main() {
            FindScore fstudent = new FindScore();
            fstudent["zhangsan", 1] = 98;
            fstudent["zhangsan", 2] = 100;
            fstudent["lisi", 1] = 80;
            fstudent["zhangsan", 3] = 90;
            //查询李四的成绩
            Console.WriteLine("李四 课程编号2 成绩为:" + fstudent["lisi", 1]);
            //查找张三的成绩
            List<Student> student = fstudent["zhangsan"];
            int result = 0;
            if (student.Count > 0)
            {
                foreach (var s in student)
                {
                    Console.WriteLine(string.Format("张三 课程编号{0} 成绩为:{1}", s.CourseID, s.Score));
                    result += s.Score;
                }
                Console.WriteLine(string.Format("张三的平均分为{0}:", result / 3));
            }
               
            else {
                Console.WriteLine("查无此人");
            }



        }
    }   
}
原文地址:https://www.cnblogs.com/jestin/p/11541722.html