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("查無此人");
            }



        }
    }   
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM