📄 indexerdemo.cs
字号:
using System;
namespace Example_2
{
/// <summary>
/// 此程序演示索引器的用法。
/// </summary>
class Student
{
// 每年的 GPA
double[] gpas = new double[4];
// 每年的 GPA 的读/写索引器
public double this[int year]
{
get
{
// 验证年级
if (year <= 0 || year > 4)
{
Console.WriteLine("错误:年级无效");
return -1;
}
// 因为数组是基于零的
int index = year - 1;
// 返回 GPA 值
return gpas[index];
}
set
{
if (year <= 0 || year > 4)
{
Console.WriteLine("年级无效");
return;
}
int index = year - 1;
// 设置新的 GPA 值
gpas[index] = value;
}
}
}
class IndexerDemo
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Student objStudent = new Student();
Console.WriteLine("输入每年的 GPA");
// 赋给每年的 GPA 值
Console.Write("一年级:");
objStudent[1] = double.Parse(Console.ReadLine());
Console.Write("二年级:");
objStudent[2] = double.Parse(Console.ReadLine());
Console.Write("三年级:");
objStudent[3] = double.Parse(Console.ReadLine());
Console.Write("四年级:");
objStudent[4] = double.Parse(Console.ReadLine());
// 检索
double total = objStudent[1] + objStudent[2] + objStudent[3] + objStudent[4];
Console.WriteLine("GPA 平均值:{0}", total/4);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -