在Java中,一般会这样使用get,set方法:
class Person{ private String name; public void setName(String name){ this.name = name; } public String getName(){ return this.name; } } public static void main(String [] args){ Person person = new Person(); person.setName("test"); String name = person.getName(); }
其中get,set是可以传参的,但是在C#中,我们一般使用属性的get,set,一般使用如下:
class Person{ private string name {set; get}; } public static void Main(){ Person person = new Person(); person.name = "test"; string name = person.name; }
可以看到这里面set,get没有参数,但是如果我们需要传入参数怎么办?在C#中有类似Java的语法,叫做索引器[Index]:
//索引器 element-type this[int index] { // get 访问器 get { // 返回 index 指定的值 } // set 访问器 set { // 设置 index 指定的值 } }
索引器使用方法如下:
using System; namespace IndexerApplication { class IndexedNames { private string[] namelist = new string[size]; static public int size = 10; public IndexedNames() { for (int i = 0; i < size; i++) namelist[i] = "N. A."; } public string this[int index] { get { string tmp; if( index >= 0 && index <= size-1 ) { tmp = namelist[index]; } else { tmp = ""; } return ( tmp ); } set { if( index >= 0 && index <= size-1 ) { namelist[index] = value; } } } static void Main(string[] args) { IndexedNames names = new IndexedNames(); names[0] = "Zara"; names[1] = "Riz"; names[2] = "Nuha"; names[3] = "Asif"; names[4] = "Davinder"; names[5] = "Sunil"; names[6] = "Rubic"; for ( int i = 0; i < IndexedNames.size; i++ ) { Console.WriteLine(names[i]); } Console.ReadKey(); } } } //输出 /* Zara Riz Nuha Asif Davinder Sunil Rubic N. A. N. A. N. A.
*/
同时我们可以重载索引器:
using System; namespace IndexerApplication { class IndexedNames { private string[] namelist = new string[size]; static public int size = 10; public IndexedNames() { for (int i = 0; i < size; i++) { namelist[i] = "N. A."; } } public string this[int index] { get { string tmp; if( index >= 0 && index <= size-1 ) { tmp = namelist[index]; } else { tmp = ""; } return ( tmp ); } set { if( index >= 0 && index <= size-1 ) { namelist[index] = value; } } } public int this[string name] { get { int index = 0; while(index < size) { if (namelist[index] == name) { return index; } index++; } return index; } } static void Main(string[] args) { IndexedNames names = new IndexedNames(); names[0] = "Zara"; names[1] = "Riz"; names[2] = "Nuha"; names[3] = "Asif"; names[4] = "Davinder"; names[5] = "Sunil"; names[6] = "Rubic"; // 使用带有 int 参数的第一个索引器 for (int i = 0; i < IndexedNames.size; i++) { Console.WriteLine(names[i]); } // 使用带有 string 参数的第二个索引器 Console.WriteLine(names["Nuha"]); Console.ReadKey(); } } } //输出 /* Zara Riz Nuha Asif Davinder Sunil Rubic N. A. N. A. N. A. 2 */