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

📅  最后修改于: 2021-09-15 01:32:10             🧑  作者: Mango

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

CSharp 中的属性和索引器之间的差异

在 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.