当前位置: 首页> 健康> 母婴 > 索引器+重载运算符

索引器+重载运算符

时间:2025/7/11 15:14:42来源:https://blog.csdn.net/m0_74236534/article/details/141528838 浏览次数:0次
索引器

索引器类似于属性,可以让类的成员被快速访问,使用一个或多个参数可以索引到类中的成员 。

声明
访问修饰符 数据类型 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);}}

该系列专栏为网课课程笔记,仅用于学习参考。 


 

关键字:索引器+重载运算符

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: