最主要区别仅仅是:索引器在获取或设置的时候需要带参数(即索引值,可以是数字,也可以是其它任何类型),属性无此要求,按理说,索引器是增强型属性.

解决方案 »

  1.   

    我這里有一個例子,請幫忙分析一下!
    using System;
    public class ScoreList
    {
    // private field Array scores
    public int[] scores = new int[5];
    // indexer
    public int this[int index]
    {
    get 
    {
    return scores[index];
    }
    set 
    {
    if (value >= 0 && value <= 10)
    {
    scores[index] = value;
    }
    }
    }
    /// <summary>
    /// property Average (read only)
    /// </summary>
    public int Average
    {
    get 
    {
    int sum = 0;
    foreach(int score in scores)
    {
    sum += score;
    }
    return sum/scores.Length;
    }
    }
    }
    class IndexSample
    {
    static void Main()
    {
    ScoreList sl = new ScoreList();
    sl[0] = 9;
    sl[1] = 8;
    sl[2] = 7;
    sl[3] = sl[4] = sl[1];
    Console.WriteLine("sl.Average() = {0}",sl.Average);
    }
    }