最近在b站学习C#(三)(BV1wx411K7rb)

文章展示了如何在C#中实现一个用于存储学生成绩的类,类中包含一个使用索引器访问的字典以及一个常量属性。索引器允许直接通过科目名称获取和设置分数,而常量则定义了一个不可变的数值。当尝试设置空值时,程序会抛出异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、索引器("ind"+Tab*2)

//主函数

try
            {
            Student stu = new Student();
            stu["Math"] = 200;
            stu["Math"] = 300;
            var mathScore = stu["Math"];
            Console.WriteLine(mathScore);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message );
            }


//类的声明
class Student
        {
            private Dictionary<string, int> scoreDictionary = new Dictionary<string, int>();
            public int? this[string subject]
            {
                get {
                    if (scoreDictionary.ContainsKey (subject ))
                    {
                        return this.scoreDictionary[subject];
                    }
                    else
                    {
                        return null;
                    }
                }
                set {
                    if (value.HasValue ==false)
                    {
                        throw new Exception("Score cannot be null.");
                    }
                    if (scoreDictionary.ContainsKey (subject))
                    {
                        this.scoreDictionary[subject] = value.Value;
                    }
                    else
                    {
                        scoreDictionary.Add(subject, value.Value);
                    }
                }
            }

        }

二、常量(属于类,const)(类的声明类和结构不可以被声明为常量)

//主函数
Console.WriteLine(Student.Amount);


//类的声明
class Student
{
public const int Amount=60;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值