C# 属性、索引

时间:2023-03-08 23:48:29
C# 属性、索引

属性(property):

public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}

简写为:

public string Name { set; get;}

索引器(index):

索引器为C#程序语言中泪的一种成员,它是的对象可以像数组一样被索引,使程序看起来更直观,更容易编写。

索引器和数组比较:

(1)索引器的索引值(Index)类型不受限制

(2)索引器允许重载

(3)索引器不是一个变量

索引器和属性的不同点

(1)属性以名称来标识,索引器以函数形式标识

(2)索引器可以被重载,属性不可以

(3)索引器不能声明为static,属性可以

要声明类或结构上的索引器,请使用this关键字,例如:

public int this[int index] //声明索引器

{

// get and set 访问

}

索引器的修饰符有:new、public、protected、internal、private、virtual、sealed、override、abstract和extern。

当索引器声明包含extern修饰符时,称该索引器为外部索引器。因为外部索引器声明不提供任何实际的实现,所以它的每个访问器声明都由一个分号组成。

索引器的签名由其形参的数量和类型组成。它不包括索引器类型或形参名。如果在同一类中声明一个以上的索引器,则它们必须具有不同的签名。

索引器值不归类为变量;因此,不能将索引器值作为ref或out参数来传递。

索引必须是实例成员。

索引器使用示例:

using System;
class IndexerRecord
{
private string [] data = new string [];
private string [] keys = {
"Author", "Publisher", "Title",
"Subject", "ISBN", "Comments"
}; //注:程序中用了两种方法来索引:
//一是整数作下标,二是字符串(关键词名)作下标
public string this[ int idx ]
{
set
{
if( idx >= && idx < data.Length )
data[ idx ] = value;
}
get
{
if( idx >= && idx < data.Length )
return data[ idx ];
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=; i<keys.Length; i++)
if( keys[i] == key ) return i;
return -;
}
static void Main()
{
IndexerRecord record = new IndexerRecord();
record[ ] = "马克-吐温";
record[ ] = "Crox出版公司";
record[ ] = "汤姆-索亚历险记";
Console.WriteLine( record[ "Title" ] );
Console.WriteLine( record[ "Author" ] );
Console.WriteLine( record[ "Publisher" ] ); Console.ReadKey(true);
}
}