C# .NET 索引器的基本使用

索引器和属性差不多,属性是一对一,而索引器是一对多而已。

(一) int 索引

class Program
{
    static void Main(string[] args)
    {
        MyClass mc = new MyClass();
        mc[0] = "胡文杰";
        mc[1] = "杨佳";
        Console.WriteLine(mc[0]);
        Console.WriteLine(mc[1]);

        Console.Read();
    }
}

class MyClass
{
    private string[] name = new string[2];
    // 关键:用 this 代替,类型也可以用 string
    public string this[int index] {
        get {
            if (index >= 0 && index < name.Length) {
                return name[index];
            }
            else {
                return name[0];
            }
        }
        set {
            if (index >=0 && index < name.Length) {
                name[index] = value;
            }
        }
    }
}

输出:

胡文杰
杨佳

string 索引

using System;


namespace RefTest
{
    class Employee
    {
        public string name;
        public string Age;
        public string Gender;

        public Employee(string n, string a, string g)
        {
            name = n;
            Age = a;
            Gender = g;
        }

        public string this[string str] {
            set {
                switch (str) {
                    case "姓名":
                        name = value;
                        break;
                    case "年龄":
                        Age = value;
                        break;
                    case "性别":
                        Gender = value;
                        break;
                        //default:
                        //throw  new Exception().Message;
                }
            }
            get {
                switch (str) {
                    case "姓名": return name;
                    case "年龄": return Age;
                    case "性别": return Gender;

                    default:
                        throw new ArgumentOutOfRangeException("index");
                }
            }
        }


        class Program
        {

            static void Main()
            {
                Employee employee = new Employee("周杰伦", "12", "男");

                Console.WriteLine(employee["姓名"] + " " + employee["年龄"] + " " + employee["性别"]);

                Console.WriteLine("\n改名:");

                employee["姓名"] = "猪八戒";

                Console.WriteLine(employee["姓名"] + " " + employee["年龄"] + " " + employee["性别"]);

                Console.ReadKey();
            }
        }
    }
}

输出:

周杰伦 12 男

改名:
猪八戒 12 男
上一篇:Java 对象和类


下一篇:《JAVA核心技术 卷I》 第四章 - 对象与类