索引器:通常用来操作数组中的元素
来源:互联网 发布:apache flink hdfs 编辑:程序博客网 时间:2024/06/11 05:13
索引器
类中保护数组对象时,可通过索引器实现方便访问
索引器用来访问类中的数组型对象元素
定义索引器与定义属性类似,一般形式为:
[修饰符] 数据类型 this[int index]
{
get //
获取数组成员指定索引的值
{
return ScoreArray[index];
}
set //
利用外部传递的value值给 数组赋值
{
ScoreArray[index] = value;
}
}
eg1:
class Program
{
static void Main(string[] args)
{
CollClass cc = new CollClass();
cc[0] = "CSharp"; //通过索引器给数组元素赋值
cc[1] = "ASP.NET";
cc[2] = "Visual Basic";
for (int i = 0; i < CollClass.intMaxNum; i++)
{
Console.WriteLine(cc[i]); //通过索引器取值
}
Console.ReadLine();
}
}
class CollClass
{
public const int intMaxNum = 3; //表示数组的长度
private string[] arrStr;
public CollClass() //构造方法
{
arrStr = new string[intMaxNum];
}
public string this[int index] //定义索引器
{
get
{
return arrStr [index ]; //通过索引器取值
}
set
{
arrStr[index] = value; //通过索引器赋值
}
}
}
eg2:
编程:
定义一个Student类,包含学号和姓名两个字段,并定义一个班级类ClassList,包含一个具有5个元素Student数组对象,利用索引器访问该数组对象,
并在主函数中 访问。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _2
{
class Student
{
public int ID;
public string name;
public Student(int ID,string name)
{
this.ID = ID;
this.name = name;
}
public void show()
{
Console.WriteLine("{0} {1}",ID ,name );
}
}
class ClassList
{
Student[] my = new Student[5];
public Student this[int index]
{
get
{
if (index < 0 || index >= my.Length)
{
return null;
}
return my[index];
}
set
{
if (index < 0 || index >= my.Length)
{
return;
}
my[index] = value;
}
}
}
public class MainClass
{
public static void Main()
{
ClassList n = new ClassList();
n[0] = new Student(1,"张三1");
n[1] = new Student(2, "张三2");
n[2] = new Student(3, "张三3");
n[3] = new Student(4, "张三4");
n[4] = new Student(5, "张三5");
for (int i = 0; i <5; i++)
{
Student my = (Student)n[i];
my.show();//通过下标获取对象中数组成员的只
}
Console.ReadLine();
}
}
}
- 索引器:通常用来操作数组中的元素
- APR中的数组元素操作
- JavaScript 通常用于操作 HTML 元素
- 练习:模板函数,用来测试数组中的元素是否按升序排列
- 数组:索引,元素,反转
- java得到元素在数组中的索引值
- js检查某个元素在数组中的索引值
- 如何删除PHP数组中的元素,并且索引重排
- js检查某个元素在数组中的索引值
- js检查某个元素在数组中的索引值
- js检查某个元素在数组中的索引值
- 求一个数组中的任何一个元素的索引
- 移除数组中的元素(操作原数组)
- 数组中元素的索引
- 数组中的元素的基本的操作方式
- jquery操作数组元素
- Jquery操作数组元素(-)
- 数组指针操作元素
- 机房收费系统重构——数据库设计
- in-house发布的ipa包,如何触发下载安装
- Android中的子菜单(SubMenu)使用案例
- 方法的分类:
- 高精度模板【高精度加减乘除模带负数判定】
- 索引器:通常用来操作数组中的元素
- Leetcode Kth Largest Element in an Array
- 第38讲-项目二-打豆豆
- spring+hibernate+struts2应用mysql数据库乱码问题
- javascript练习题
- 高效的用户数据报协议 和 可靠的传输控制协议
- spring+hibernate+struts2应用mysql数据库乱码问题
- 嵌入式linux设置时区
- mongodb数据迁移2种方式比较(推荐)