C#中索引器的实现过程
2025-02-10 16:23
钟铧若岩
阅读(121)
评论(0)
收藏
举报
在 C# 中,索引器是一种特殊的属性,它允许对象像数组一样通过索引来访问其元素。下面为你详细介绍索引器的实现过程以及索引类型的相关情况。
索引器的实现过程
1. 基本语法
索引器使用 this 关键字定义,并且需要指定索引的类型和返回值类型。以下是一个简单的索引器实现示例,该示例创建了一个自定义的字符串数组类,并使用索引器来访问数组元素:
using System;
class StringArray
{
private string[] array;
public StringArray(int size)
{
array = new string[size];
}
// 索引器定义
public string this[int index]
{
get
{
if (index < 0 || index >= array.Length)
{
throw new IndexOutOfRangeException("索引超出范围");
}
return array[index];
}
set
{
if (index < 0 || index >= array.Length)
{
throw new IndexOutOfRangeException("索引超出范围");
}
array[index] = value;
}
}
}
class Program
{
static void Main()
{
StringArray strArray = new StringArray(3);
strArray[0] = "apple";
strArray[1] = "banana";
strArray[2] = "cherry";
Console.WriteLine(strArray[1]); // 输出: banana
}
}
2. 代码解释
定义存储数据的字段:在 StringArray 类中,定义了一个 string 类型的数组 array 用于存储数据。
索引器定义:使用 this[int index] 定义索引器,其中 int 是索引的类型,表示通过整数索引来访问元素。get 访问器用于获取指定索引位置的元素,set 访问器用于设置指定索引位置的元素。
使用索引器:在 Main 方法中,创建了 StringArray 类的实例,并使用索引器来设置和获取数组元素。
索引器的索引类型
索引器并不只能根据数字进行索引,实际上,索引器可以使用任意类型作为索引,只要该类型适合作为查找元素的键。以下是一些不同索引类型的示例:
1. 字符串作为索引
using System;
using System.Collections.Generic;
class DictionaryExample
{
private Dictionary
// 字符串索引器
public int this[string key]
{
get
{
if (dictionary.ContainsKey(key))
{
return dictionary[key];
}
return 0;
}
set
{
dictionary[key] = value;
}
}
}
class Program
{
static void Main()
{
DictionaryExample dict = new DictionaryExample();
dict["apple"] = 10;
dict["banana"] = 20;
Console.WriteLine(dict["banana"]); // 输出: 20
}
}
在这个示例中,使用 string 类型作为索引器的索引,通过字符串键来访问字典中的值。
2. 自定义类型作为索引
using System;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class PersonCollection
{
private Person[] people;
public PersonCollection(int size)
{
people = new Person[size];
}
// 自定义类型索引器
public Person this[Person person]
{
get
{
foreach (var p in people)
{
if (p != null && p.Name == person.Name && p.Age == person.Age)
{
return p;
}
}
return null;
}
set
{
for (int i = 0; i < people.Length; i++)
{
if (people[i] == null)
{
people[i] = value;
break;
}
}
}
}
}
class Program
{
static void Main()
{
PersonCollection collection = new PersonCollection(2);
Person person1 = new Person { Name = "Alice", Age = 25 };
collection[person1] = person1;
Person result = collection[person1];
if (result != null)
{
Console.WriteLine($"找到人员: {result.Name}, 年龄: {result.Age}");
}
}
}
在这个示例中,使用自定义的 Person 类型作为索引器的索引,通过 Person 对象来查找和存储人员信息。
综上所述,C# 中的索引器可以使用多种类型作为索引,并不局限于数字类型,具体使用哪种索引类型取决于实际的业务需求。
刷新页面返回顶部
About
博客园 © 2004-2025
浙公网安备 33010602011771号
浙ICP备2021040463号-3