索引器練習 照片 相冊 索引器

定義一個照片類。屬性:名稱大小
定義一個相冊類。獲取保存多個照片對象,獲取相冊當中的照片對象(獲取所有,獲取第幾張,根據照片名稱獲取)並顯示
頭一次幫人答題--自己加油!
using System;

namespace PhotoIndexer
{
    public class Photo
    {
       
        private string title;
        private int size;

        public Photo(string title)
        {
            this.title = title;
        }
        public Photo(string title,int size)
        {
            this.title = title;
            this.size = size;
        }

        public string Title
        {
            get
            {
                return this.title;
            }
            set
            {
                this.title = value;
            }
        }

        public int Size
        {
            get
            {
                return this.size;
            }
            set
            {
                this.size = value;
            }
        }
    }
    public class Album
    {
        private Photo[] photos;
        
        public Album(int numbr)
        {
            photos=new Photo[numbr];  
        }

        /// <summary>
        /// 根據序號索引
        /// </summary>
        /// <param name="index">索引</param>
        /// <returns></returns>
        public Photo this[int index]
        {
            get
            {
                return photos[index];
            }
            set
            {
                photos[index] = value;
            }
        }

        /// <summary>
        /// 根據文件名索引
        /// </summary>
        /// <param name="title">文件名</param>
        /// <returns></returns>
        public Photo this[string title]
        {
            get
            {
                for (int i = 0; i < photos.Length;i++ )
                {
                    if(photos[i].Title==title)
                    {
                        return photos[i];
                    }
                }
                Console.WriteLine("此相冊沒有找到文件名爲{0}的照片",title);
                return null;
            }
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Photo photo1=new Photo("photo1",15);
            Photo zhangsan = new Photo("zhangsan",20);
            Photo lisi  =new Photo("lisi",60);
            Album allphoto = new Album(3);
            allphoto[0] = photo1;
            allphoto[1] = zhangsan;
            allphoto[2] = lisi;
            for (int i = 0; i < 3; i++) //獲取所有
            {
                Console.WriteLine("all name that is"+allphoto[i].Title);
            }
            Console.ReadKey();

            Console.WriteLine("the sceond photo is ["+allphoto[1].Title +"] and he's photo size is "+allphoto[1].Size);//獲取第幾張
            Console.ReadKey();

            Console.WriteLine("name is lisi's photo is ["+allphoto["lisi"].Title+"] and he's photo size is "+allphoto["lisi"].Size);  //根據名字查找
            Console.ReadKey();
        
        }
    }
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章