c#索引訪問器再探_get_set之訪問控制存取

wisdomone1發表於2012-03-13


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

namespace ConsoleApplication1
{
    class Team
    {
        private int[] arr = new int[100];
        public int this[int index]   // Indexer declaration
        {
            get
            {
                // Check the index limits.
                //if (index < 0 || index >= 100)
                if ((index == 3)||(index==5))
                {
                    return arr[index];
                }
                else
                {
                    //其它除了3與5索引的元素,在呼叫方查詢時全是777
                    return 777;
                }
            }
            set
            {
                //索引訪問器的供值優先順序高於 呼叫此類物件的供值語句 Team test = new Team(); test[3] = 256;
                
                
                if (index == 3 || index == 5)
                {
                    arr[index] = 233444;
                }
            }
        }
        
    }
}


    呼叫上述包含索引訪問器的TEAM類

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Team test = new Team();
            // 3與5號索引有資料,其它全是元素全是0
            注:此直接供值被team類的索引訪問器set屏掉
            //即set優先極高於下述2行程式碼
            test[3] = 256;
            test[5] = 1024;
            for (int i = 0; i <= 10; i++)
            {
                //使用的是get索引訪問器
                System.Console.WriteLine("Element #{0} = {1}", i, test[i]);
            }
            Console.ReadKey();
        }
    }
}


除錯結果
Element #0 = 777 //對應get的else分支
Element #1 = 777
Element #2 = 777
Element #3 = 233444 //對應set部分
Element #4 = 777
Element #5 = 233444
Element #6 = 777
Element #7 = 777
Element #8 = 777
Element #9 = 777
Element #10 = 777

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9240380/viewspace-718429/,如需轉載,請註明出處,否則將追究法律責任。

相關文章