The difference between C # indexer and Array

1. Type indexer index value is not limited to an integer

2. The index allows overloading

3. The index is not a variable

4. The index is a function of this identification signature scheme, using the name and the attribute ID, name can be arbitrarily

The index can not be declared with the static properties can. Indexer will always belong to an instance member, and therefore can not be declared as 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 ;
             // query results John Doe 
            Console.WriteLine ( " John Doe No. 2 course score: " + fstudent [ " lisi " , 1 ]);
             // Find Joe Smith scores
            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("John's Average 0} {: " , Result / . 3 )); 
            } 
               
            the else { 
                Console.WriteLine ( " no such person " ); 
            } 



        } 
    }    
}

 

Guess you like

Origin www.cnblogs.com/jestin/p/11541722.html