索引器+重载运算符

索引器

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

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

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


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值