一.有关索引器
using System;
//indexer:一个对象可以像数组一样被索引
namespace _015_索引器
{
//索引器的写法
public abstract class IndexerName
{
//int index;//不能这么写去替换下面的int index,语法很严格
public abstract string this[int index]
{
get;
set;
}
}
public class IndexerClass
{
private int age;
private string name;
public int this[int index]
{
get
{
return age;
}
set
{
age = value;
}
}
//一个类中不能有两个索引器,因为会引起误解,无法确定到底使用哪个索引器
// public string this[int index]
// {
// get
// {
// return name;
// }
// set
// {
// name = value;
// }
// }
private string code;
public string this[float index]//为什么这里float不报错呢?因为这里只是控制索引的序号的写法,如果是 string index,那么
//只要访问时格式为:实例化对象[string类型的index]也可以访问
{
get
{
return code;
}
set
{
code = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
二.索引器的理解
using System;
namespace _016_索引器的理解
{
public class IndexerName
{
//这里对int值的修饰符为const或者static都没有问题
//const表示是个常量不可修改
//static表示可以进行修改
//但是不可以两个一起写
// 用修饰符static声明的字段为静态字段。不管包含该静态字段的类生成多少个对象或根本无对象,该字段都只有一个实例,静态字段不能被撤销。必须采用如下方法引用静态字段:类名.静态字段名。
//如果类中定义的字段不使用修饰符static,该字段为实例字段,每创建该类的一个对象,在对象内创建一个该字段实例,创建它的对象被撤销,该字段对象也被撤销,实例字段采用如下方法引用:实例名.实例字段名。
//用const修饰符声明的字段为常量,常量只能在声明中初始化,以后不能再修改。
public const int size = 5;
// public static int size = 5;
private string[] stringArray = new string[size];
public IndexerName()
{
for (int i = 0; i < size; i++)
{
stringArray[i] = "null";
}
}
public string this[int index]
{
//这个基本思路可以这么理解
//先通过set将值先传进来,然后get赋值给temp局部变量传出去
get
{
string temp="";
if(index >=0&&index<=size-1)
{
temp = stringArray[index];
}
else
{
temp = "";
}
return temp;
}
set
{
if(index>=0&&index<=size-1)
{
stringArray[index] = value;
}
}
}
}
class Program
{
static void Main(string[] args)
{
IndexerName indexerName = new IndexerName();
indexerName[0] = "a" ;
indexerName[1] = "b";
indexerName[2] = "c";
for (int i = 0; i < IndexerName.size; i++)//会报错,无法使用实例引用来访问成员,因为如果用const修饰, 可以直接用类名调用
{
Console.WriteLine(indexerName[i]);
}
}
}
}
三.索引器重载
using System;
namespace _017_索引器重载
{
public class IndexClass
{
public static int size = 5;
private string[] stringArray = new string[size];
public IndexClass()
{
for (int i = 0; i < size; i++)
{
stringArray[i] = "null";
}
}
public string this[int index]
{
get
{
string temp;
if(index>=0&&index<=size-1)
{
temp = stringArray[index];
}
else
{
temp = "";
}
return temp;
}
set
{
if(index>=0&&index<=size-1)
{
stringArray[index] = value;
}
}
}
public int this[string str]
{
get
{
int index = 0;
while(index<size)
{
if(stringArray[index]==str )
{
return index;
}
index++;
}
return index;
}
}
}
class Program
{
static void Main(string[] args)
{
IndexClass indexClass = new IndexClass();
indexClass[0] = "a";
indexClass[1] = "b";
indexClass[2] = "c";
indexClass[3] = "d";
indexClass[4] = "e";
Console.WriteLine(indexClass["c"]);
for (int i = 0; i < IndexClass.size; i++)
{
Console.WriteLine(indexClass[i]);
}
}
}
}
浙公网安备 33010602011771号