C#中的索引器
在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
*/
總結
- 上一篇: 轻钢结构别墅厂家(轻钢结构别墅每平米价格
- 下一篇: 南京富二代杀妻案遗体照(南京富二代杀妻真