索引器
特点:数组属性只能根据下标(索引)来访问,索引器可以为任意类型
索引器可以被重载
可以使用更灵活的方式访问,定义访问方式
索引器小例子
Student类
class Student
{
//存放学生信息
private Hashtable names = new Hashtable();
//定义一个索引器,通过下标查询值
public string this[int index]
{
get
{
if (index < 2)
{
return names[index].ToString();
}
return null;
}
set
{
if (index < 2)
{
names[index] = value;
}
}
}
//定义一个索引器,通过名字查找
public int this[string name]
{
get
{
foreach (DictionaryEntry item in names)
{
if (item.Value.ToString() == name)
{
return Convert.ToInt32(item.Key);
}
}
return -1;
}
set
{
names.Add(value,name);
}
}
}
Main方法
class Program
{
static void Main(string[] args)
{
Student stu = new Student();
stu[0] = "张三";
stu[1] = "李四";
//通过索引查找姓名
Console.WriteLine(stu[0]);
//通过名字查找索引值
Console.WriteLine(stu["李四"]);
Console.ReadLine();
}
}
结果
静态类 (static class 类名)
静态类只用于包含静态成员的类型,他不能被实例化
静态类的特性是防止继承,防止外部来创建对象
static class Person
{
public int age;//错误
static string name;//正确
}
注意:
1.静态类不能有构造函数
2.静态类不能有非静态成员,不能实例化对象
3.静态类成员不能有protected或protectedinternal访问修饰符
4.不能被继承