C# 语法练习(13): 类[五] 索引器


通过索引器可以方便使用类中的数组(或集合)成员:
using System;

class MyClass
{
    private float[] fs = new float[3] { 1.1f, 2.2f, 3.3f };

    /* 属性 */
    public int Length
    { 
        get { return fs.Length; }
        set { fs = new float[value]; }
    }

    /* 索引器 */
    public float this[int n]
    {
        get { return fs[n]; }
        set { fs[n] = value; }
    }
}


class Program
{
    static void Main()
    {
        MyClass obj = new MyClass();

        for (int i = 0; i < obj.Length; i++) Console.WriteLine(obj[i]); // 1.1/2.2/3.3

        for (int i = 0; i < obj.Length; i++) obj[i] += 5.5f;
        for (int i = 0; i < obj.Length; i++) Console.WriteLine(obj[i]); // 6.6/7.7/8.8

        obj.Length = 5;
        for (int i = 0; i < obj.Length; i++) Console.WriteLine(obj[i]); // 0/0/0/0/0

        Console.ReadKey();
    }
}


可用其他值做索引类型:
using System;

class MyClass
{
    public int this[string str] 
    { 
        get { return str.Length; } 
    }
}


class Program
{
    static void Main()
    {
        MyClass obj = new MyClass();

        Console.WriteLine(obj["123"]);  // 3
        Console.WriteLine(obj["abcd"]); // 4

        Console.ReadKey();
    }
}


原文地址:https://www.cnblogs.com/del/p/1367419.html