属性与索引之间的比较

来自MSDN的 属性与索引器之间的比较

索引器与属性类似。除下表中显示的差别外,为属性访问器定义的所有规则同样适用于索引器访问器。

属性 索引器

允许调用方法,如同它们是公共数据成员。

允许调用对象上的方法,如同对象是一个数组。

可通过简单的名称进行访问。

可通过索引器进行访问。

可以为静态成员或实例成员。

必须为实例成员。

属性的 get 访问器没有参数。

索引器的 get 访问器具有与索引器相同的形参表。

属性的 set 访问器包含隐式 value 参数。

除了 value 参数外,索引器的 set 访问器还具有与索引器相同的形参表。

 

属性例子:

 

C#属性代码
   
     
class TimePeriod
{
private double seconds;

public double Hours
{
get { return seconds / 3600 ; }
set { seconds = value * 3600 ; }
}
}

class Program
{
static void Main()
{
TimePeriod t
= new TimePeriod();

// Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = 24 ;

// Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine( " Time in hours: " + t.Hours);
}
}

 

索引例子:

 

C# 索引例子
   
     
class SampleCollection < T >
{
private T[] arr = new T[ 100 ];
public T this [ int i]
{
get
{
return arr[i];
}
set
{
arr[i]
= value;
}
}
}

// This class shows how client code uses the indexer
class Program
{
static void Main( string [] args)
{
SampleCollection
< string > stringCollection = new SampleCollection < string > ();
stringCollection[
0 ] = " Hello, World " ;
System.Console.WriteLine(stringCollection[
0 ]);
}
}

 

你可能感兴趣的:(索引)