public string this[int i]{}是什么东西,怎么用

具体程序如下:

using System;
class IndexerRecord
{
    private string[] data = new string[6];

    //定义了一个字符串数组data

    private string[] keys = {"Author","Publish","Title","subject","isbn","comments"};
    //定义一个字符串型数组keys并初始化

    /// <summary>
    /// this指的是什么?
    /// </summary>
    /// <param name="idx"></param>
    /// <returns></returns>
    public string this[int idx]  
    {
        set
        {
            if (idx >= 0 && idx < data.Length)
            {
                data[idx] = value;            
            }
        }
        get
        {
            if (idx >= 0 && idx < data.Length)
            {
                //返回什么,下面还返回空值?
                return data[idx];  
            }
            else
            {
                return null;
            }
        }
    }
    
    public string this[string key]
    {
        set
        {
            int idx = FindKey(key); 
            this[idx] = value; 
        }
        get
        {
            return this[FindKey(key)];
        }
    }

    private int FindKey(string key)
    {
        for (int i = 0; i < keys.Length; i++)
        {
            if (keys[i] == key)
            {
                return i;
            }
        }
        return -1;

    }
    
    /// <summary>
    /// Main
    /// </summary>
    static void Main()
    {
        IndexerRecord record = new IndexerRecord();
        //这里不是定义了数组,是新建了一个IndexRecord的对象
        record[0] = "马克吐温"; //数组元素0 赋值
        record[1] = "Crox出版公司";  //数组元素1 赋值
        record[2] = "汤姆-索亚历险记";  //数组元素2 赋值
        Console.WriteLine(record["Title"]);
        Console.WriteLine(record["Author"]);
        Console.WriteLine(record["Publisher"]);

        record.data.SetValue("intro", 5);//设定第6个的值为intro
        /*也有GetValue方法,只不过是用来取值的*/
        Console.WriteLine(record[6]);//输出第6个的值
    }
}

public string this[int nIndex]其中this的作用是什么:

你写的是一个索引函数的定义,this在这里代表对当前对象本身的引用。

例如你在一个名为Contact的类中定义了这个索引函数,实例化一个这个类的对象Contact c = new Contact();访问索引函数的形式形如c[1],定义里的this就代表这里的c。

另外注意索引函数不能是静态的。

posted @ 2014-07-22 21:38  邹邹  Views(1716)  Comments(0)    收藏  举报