📜  C#中的属性和索引器之间的区别

📅  最后修改于: 2021-05-29 17:23:06             🧑  作者: Mango

C#中的属性是使用访问修饰符设置和检索以安全方式声明的字段的值的命名成员。通过仅定义重要动作并隐藏其实现,属性用于抽象化和封装对类字段的访问。属性通过描述的名称调用,并且可以声明为静态成员或实例成员。

尖锐属性与索引之间的差异

在C#中声明属性的语法:

[access_modifier] [return_type] [PropertyName]  
{
//body of property
}

C#中的索引器是充当数组的数据成员,并允许您以相同的方式访问要索引的对象内的数据。索引器始终声明为实例成员,而不声明为静态成员。索引器的实现方式与属性相同,不同之处在于索引器的声明必须至少具有一个参数。

在C#中创建索引器的语法:

[access_modifier] [return_type] this [parameter]
{
  get 
  {
     // return value
  }
  set 
  {
    // return value
  }
}

C#中的属性和索引器之间的区别

Properties Indexers
1. Properties are declared by giving a unique name. Indexers are declared without giving a name.
2. Properties are identified by the names While indexers are identified by the signatures.
3. Properties can be declared as a static or an instance member. Indexers are always declared as instance member, never as static member.
4. Properties are invoked through a described name. Indexers are invoked using an index of the created object.
5. Properties does not needs this keyword in their creation. Indexers needs this keyword in their keyword.
6. A get accessor of a property does not have any parameters. A get accessor of a property contains the list of same proper parameters as indexers.