设为首页 加入收藏

TOP

C#索引器与数组的区别
2019-09-19 11:09:57 】 浏览:44
Tags:索引 区别

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



        }
    }   
}

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇identityServer3+ADFS实现域用户.. 下一篇ASP.NET Core CMS管理后台

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目