Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace IndexTest
{
class Program
{
static void Main(string[] args)
{
Teame teme = new Teame();
Student student1 = new Student(15, "张三");
Student student2=new Student(16,"李四");
teme[0] = student1;
teme[1]=student2;
Console.WriteLine("学生{0},他的年龄为{1}", teme[0].Name, teme[0].Age);
}
}
class Teame
{
Student[] student = new Student[10];
/**//*****************索引器***********************/
public Student this[int index] //通过数组下标
{
get { return student[index];}
set { student[index] = value; }
}
public Student this[string name] //通过姓名
{
get
{
foreach (Student item in student)
{
if(item.Name.Equals(name))
{
return item;
}
}
return null;
}
}
/**//******************************************/
}
class Student
{
public Student(int age, string name)
{
this._age = age;
this._name = name;
}
int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
}
以前经常用C#的索引器,却不知道自己一直在使用.好悲剧,今天了解了下原理感觉真的很不错,写个例子,做下记录
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace IndexTest
{
class Program
{
static void Main(string[] args)
{
Teame teme = new Teame();
Student student1 = new Student(15, "张三");
Student student2=new Student(16,"李四");
teme[0] = student1;
teme[1]=student2;
Console.WriteLine("学生{0},他的年龄为{1}", teme[0].Name, teme[0].Age);
}
}
class Teame
{
Student[] student = new Student[10];
/**//*****************索引器***********************/
public Student this[int index] //通过数组下标
{
get { return student[index];}
set { student[index] = value; }
}
public Student this[string name] //通过姓名
{
get
{
foreach (Student item in student)
{
if(item.Name.Equals(name))
{
return item;
}
}
return null;
}
}
/**//******************************************/
}
class Student
{
public Student(int age, string name)
{
this._age = age;
this._name = name;
}
int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
}