using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 索引器
{
class Program
{
static void Main(string[] args)
{
Person p1 = new Person();
p1[0] = "大毛";
p1[1] = "二毛";
Console.WriteLine("{0} {1}", p1[0], p1[1]);
Console.ReadKey();
}
}
public class Person
{
private string FirstName;
private string SecondName;
//索引器写法 索引器也可以重载 public string this[int index,string name]
//string 索引器类型
public string this[int index]
{
set
{
if (index == 0)
{
FirstName = value;
}
else if(index ==1)
{
SecondName = value;
}
else
{
throw new Exception("参数异常");
}
}
get
{
if (index == 0)
{
return FirstName;
}
else if (index == 1)
{
return SecondName;
}
else
{
throw new Exception("参数异常");
}
}
//和属性相似,也可以不写set,使之成为只读的索引器。就如string类的索引器一样。
}
}
}
C#学习笔记(十九) --索引器
最新推荐文章于 2024-01-11 11:31:27 发布