一分钟带你了解c#中的索引器

发布时间:2020-11-05 16:11:41 作者:Leah
来源:亿速云 阅读:198

本篇文章给大家分享的是有关一分钟带你了解c#中的索引器,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

概念

索引器(Indexer) 允许类中的对象可以像数组那样方便、直观的被引用。当为类定义一个索引器时,该类的行为就会像一个 虚拟数组(virtual array) 一样。

索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用。

可以使用数组访问运算符([ ])来访问该类的实例。

索引器的行为的声明在某种程度上类似于属性(property)。属性可使用 get 和 set 访问器来定义索引器。但是属性返回或设置的是一个特定的数据成员,而索引器返回或设置对象实例的一个特定值。

定义一个一维数组的索引器:

element-type this[int index]
{
 // get 访问器
 get
 {
  // 返回 index 指定的值
 }
 
 // set 访问器
 set
 {
  // 设置 index 指定的值
 }
}

提示:索引器必须以this关键字定义,this 是类实例化之后的对象

实例:

using System;
 
namespace C_Pro
{
 public class Student
 {
  private string name;
  private string grade;
 
  public string Name
  {
   get {return name; }
   set {name = value; }
  }
 
   public string Grade
  {
   get {return grade; }
   set {grade = value; }
  }
 
  // 定义索引器
  public string this[int index]
  {
   get
   {
    if (index == 0) return name;
    else if (index == 1) return grade;
    else return null;
   }
   set
   {
    if (index == 0) name = value;
    else if (index == 1) grade = value;
   }
  }
  static void Main(string[] args)
  {
   Student s = new Student();
   s[0] = "Jeson";
   s[1] = "First-year";
 
   Console.WriteLine(s.Name);
   Console.WriteLine(s.Grade);
   Console.ReadKey();
  }
 }
}

运行后结果:

Jeson

First-year

重载索引器

索引器(Indexer)可被重载。索引器声明的时候也可带有多个参数,且每个参数可以是不同的类型。没有必要让索引器必须是整型的。C# 允许索引器可以是其他类型,例如,字符串类型。

using System;
 
namespace C_Pro
{
 public class IndexedNames
 {
  private string[] namelist = {"a", "b", "c", "d"};
 
  // 输入namelist的index返回对应的值
  public string this[int index]
  {
   get
   {
    return namelist[index];
   }
   set
   {
    namelist[index] = value;
   }
  }
 
  // 输入namelist的值,返回对应的索引
   public int this[string name]
  {
   get
   {
    for (int i=0; i<namelist.Length; i++)
    {
     if (namelist[i] == name) return i;
    }
     
    return -1;
   }
 
  }
 
  static void Main(string[] args)
  {
 
   IndexedNames name = new IndexedNames();
    
   Console.WriteLine(name[1]);
   Console.WriteLine(name["a"]);
 
  }
 }
}

运行后结果:

b

0

索引器与数组的区别:

索引器与属性的区别:

以上就是一分钟带你了解c#中的索引器,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. 带你全面了解QinQ
  2. 带你了解Spring中的各种Utils

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

索引器

上一篇:一文读懂Go 字符串指纹

下一篇:django中blank和null的区别有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》