您当前的位置: 首页 >  c#

令狐掌门

暂无认证

  • 3浏览

    0关注

    513博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C#类索引器

令狐掌门 发布时间:2021-02-16 12:03:43 ,浏览量:3

在C#中,除了用属性给字段设置值,还可以用索引器,例如下面的Student类,有3个字段,利用索引器给各个字段赋值,获取值,索引器内部写法就是普通函数的写法,索引器的格式

public    返回类型   this[参数列表]

代码如下:

using System;
using System.Collections.Generic;
using System.Text;

namespace 类的索引器
{
    class Student
    {
        string _Name;
        string _Address;
        string _Hobby;

        //索引器
        public string this[int index]
        {
            set
            {
                switch(index)
                {
                    case 0:
                        _Name = value;
                        break;

                    case 1:
                        _Address = value;
                        break;

                    case 2:
                        _Hobby = value;
                        break;

                    default:
                        throw new ArgumentOutOfRangeException("index");
                }
            }

            get
            {
                switch(index)
                {
                    case 0: return _Name;
                    case 1: return _Address;
                    case 2: return _Hobby;
                    default: throw new ArgumentOutOfRangeException("index");
                }
            }
        }

        public void SayHello()
        {
            Console.WriteLine("我叫{0}, 地址是{1}, 我喜欢{2}", this[0], this[1], this[2]);
        }
    }
}

​ 在Main方法中测试,代码如下:

static void Main(string[] args)
{
    Student st = new Student();
    st[0] = "张三";
    st[1] = "银河路127号";
    st[2] = "飞行";

    st.SayHello();

    Console.ReadKey();
}

​ 由此可知,索引器可以同时给多个字段赋值,比属性功能多些。

​ 同时索引器还可以重载,例如下面的例子:

//索引器重载
class MyClass
{
    public string this[int index]
    {
        set { ... }
        get { ... }
    }

    public string this[int index1, int index2]
    {
        set { ... }
        get { ... }
    }

    public string this[float index1]
    {
        set { ... }
        get { ... }
    }
}

​ 这和函数的重载相同,参数列表不同。

关注
打赏
1652240117
查看更多评论
立即登录/注册

微信扫码登录

0.1217s