在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 = ;
public IndexedNames()
{
for (int i = ; i < size; i++)
namelist[i] = "N. A.";
}
public string this[int index]
{
get
{
string tmp; if( index >= && index <= size- )
{
tmp = namelist[index];
}
else
{
tmp = "";
} return ( tmp );
}
set
{
if( index >= && index <= size- )
{
namelist[index] = value;
}
}
} static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[] = "Zara";
names[] = "Riz";
names[] = "Nuha";
names[] = "Asif";
names[] = "Davinder";
names[] = "Sunil";
names[] = "Rubic";
for ( int i = ; 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 = ;
public IndexedNames()
{
for (int i = ; i < size; i++)
{
namelist[i] = "N. A.";
}
}
public string this[int index]
{
get
{
string tmp; if( index >= && index <= size- )
{
tmp = namelist[index];
}
else
{
tmp = "";
} return ( tmp );
}
set
{
if( index >= && index <= size- )
{
namelist[index] = value;
}
}
}
public int this[string name]
{
get
{
int index = ;
while(index < size)
{
if (namelist[index] == name)
{
return index;
}
index++;
}
return index;
} } static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[] = "Zara";
names[] = "Riz";
names[] = "Nuha";
names[] = "Asif";
names[] = "Davinder";
names[] = "Sunil";
names[] = "Rubic";
// 使用带有 int 参数的第一个索引器
for (int i = ; 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
*/
05-11 22:53