索引器
namespace 索引器
{
class Program
{
static void Main(string[] args)
{
Person p1 = new Person();
p1[1] = "小明";
Console.WriteLine(p1[1] + p1[2]);
Console.ReadKey();
}
}
public class Person
{
private string firstName = "大毛";
private string secondName = "二毛";
//下面这个就是索引器
public string this[int index]//索引可以有不止一个参数,set和get可以只有一个
{
set
{
if (index == 1)
{
firstName = value;
}
else if (index == 2)
{
secondName = value;
}
else
{
throw new Exception("输入的值不合适");
}
}
get
{
if (index == 1)
{
return firstName;
}
else if (index == 2)
{
return secondName;
}
else
{
throw new Exception("输入的值不合适");
}
}
}
}
}