索引器
索引器类似于属性,可以让类的成员被快速访问,使用一个或多个参数可以索引到类中的成员 。
声明
访问修饰符 数据类型 this[数据类型 索引参数]
{
get{return} //读
set{字段=value} //写
}
使用:对象名[索引参数]
如何在函数中抛出异常
使用throw关键
new IndexOutOfRangeException();
一旦抛出异常,程序就会终止在抛出异常的地方。
例:
class Person
{
string name;
string sex;
string age;
string hobby;
public Person(string name, string sex, string age, string hobby)
{
this.name = name;
this.sex = sex;
this.age = age;
this.hobby = hobby;
}
public string this[int index]
{
get
{
switch (index)
{
case 0:
return name;
case 1:
return sex;
case 2:
return age;
case 3:
return hobby;
default:
throw new IndexOutOfRangeException();
}
}
}
}
internal class Program
{
static void Main(string[] args)
{
Person p = new Person("小明","男", "17", "看电影");
Console.WriteLine(p[4]);
}
}
运行结果:
重载运算符
以下为可进行重载的运算符:
一元运算符:+,-,!,~,++,--,true,false
二元运算符:+,-,*,/,%,&,|,^,<<,>>
比较运算符:==,!=,<,>,<=,>=
operator关键字(重载运算符)
让我们自定义的数据类型可以通过运算符进行运算
访问修饰符 static 返回类型 operator 运算符(){运算内容以及返回结果}
应用示例:
struct Vector2
{
int x, y;
public Vector2(int x, int y)
{
this.x = x;
this.y = y;
}
public static Vector2 operator +(Vector2 a,Vector2 b)
{
//Vector2 ;
return new Vector2(a.x + b.x, a.y + b.y);
}
public override string ToString()
{
return String.Format("({0},{1})", x, y);
}
}
class Program
{
static void Main(string[] args)
{
Vector2 pointA = new Vector2(1, 1);
Vector2 dir = new Vector2(2, 3);
Vector2 pointB = pointA + dir;
Console.WriteLine(pointB);
}
}
该系列专栏为网课课程笔记,仅用于学习参考。