2012-10-18 87 views
1

你能描述一下它的功能吗?我在其中一个项目中遇到过它,但不知道它是如何工作的。类中的奇怪属性

public object this[int i] 
{ 
    get { return columnValues[i]; } 
} 
+5

[已编入索引的属性](http://msdn.microsoft.com/zh-cn/library/aa288464(v = vs.71).aspx)。 –

+2

另请参阅[索引器](http://msdn.microsoft.com/zh-cn/library/vstudio/6x16t2tx.aspx)。 – Jon

回答

4

这就是所谓的索引,用于索引,比如我们用它来从字符串获得字符。你可以准备一下吧here,或here

string str = "heel"; 

char chr = str[0]; 

这是如何索引可以为类

class Sentence 
{ 
    string[] words = "The quick brown fox".Split(); 
    public string this [int wordNum] // indexer 
    { 
     get { return words [wordNum]; } 
     set { words [wordNum] = value; } 
    } 
} 

Sentence s = new Sentence(); 
Console.WriteLine (s[3]); // fox 
s[3] = "kangaroo"; 
Console.WriteLine (s[3]); // kangaroo 
+0

非常清楚,谢谢:) Ppl每天学习:P – Nickon

+0

不客气。 – Adil

3

进行这就是所谓的indexer。它允许你在你自己的类型中使用方括号。

+2

+1对于索引者的完全不相关的积极副作用。 =) –