C#索引器:在集合或数组中取出某一个元素 举例

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:03   2423   0

1.语法:

[访问修饰符] 数据类型 this[参数列表]

{

get

{ 获取索引器的内容 }

set

{ 设置索引器的内容 }

}


2.举例

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

namespace IndexerUsing
{
    class Photo
    {
       
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public Photo() { }
        public Photo(string name)
        {
            this.name = name;
        }
    }
    class Album
    {
        private Photo[] _photos;
        public Album()
        { }
        public Album(int count)
        {
            _photos = new Photo[count];
        }
        public Photo this[int index]
        {
            get
            {
                if (index < 0 || index > _photos.Length)
                    return null;
                else
                    return _photos[index];
            }
            set
            {
                if (index < 0 || index > _photos.Length)
                    return;
                else
                    _photos[index] = value;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Album album = new Album(3);
            Photo photo1 = new Photo("王云鹏");
            Photo photo2 = new Photo("黄利云");
            Photo photo3 = new Photo("李文平");
            album[0] = photo1;
            album[1] = photo2;
            album[2] = photo3;
            Console.WriteLine("输入第一张照片:{0}", album[0].Name);

        }
    }
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP