C#中的索引器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace 索引器
{
    class Program
    {
        static void Main(string[] args)
        {
            MyIndexer myindex = new MyIndexer();
            myindex[0] = 23;
            myindex[3] = 2;
            for (int i = 0; i < myindex.Length(); i++)
            {
                Console.WriteLine("arr[{0}]={1}", i, myindex[i]);

            }

    //对象数组
            MyIndexer []index1 = new MyIndexer[5];
            for (int i = 0; i < index1.Length; i++)
            {
                index1[i] = new MyIndexer();
            }
            index1[1][0] = 20;
            Console.WriteLine(index1[1][0]);

        }
    }
    class MyIndexer
    {
        private int[] arr = new int[5];
        public int this[int index]
        {
            get 
            {
                if (index >= 0 && index <= 4) return arr[index];
                else return 0;
            }
            set
            {
                if (index >= 0 && index <= 4) arr[index] = value;
            }
        }
        public int Length()
        { 
             return arr.Length;
        }
    }

}

//使用索引器访问离散字段

namespace 索引器
{
    class Program
    {
        static void Main(string[] args)
        {
            PhoneBook phoneBook = new PhoneBook("张彬");
            phoneBook["officephone"] = "officephone123";
            phoneBook["homephone"] = "homePhone23";
            phoneBook["mobilePhone"] = "mobilephone12";
            phoneBook.PrintPhoneBook();
        }
    }
    //使用索引器访问离散字段
    class PhoneBook
    {
        private string name;
        private string officePhone;
        private string homePhone;
        private string mobilePhone;
        public PhoneBook() { }
        public PhoneBook(string name)
        {
            this.name = name;
        }
        public string Name
        {
            get 
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
        public string this[string type]
        {
            get 
            {
                switch (type.ToLower())
                {
                    case "officephone": return officePhone;
                    case "homephone": return homePhone;
                    case "mobilephone": return mobilePhone;
                    default: return null;
                }            
            }
            set
            {
                switch (type.ToLower())
                {
                    case "officephone": officePhone = value; break;
                    case "homephone": homePhone = value; break;
                    case "mobilephone": mobilePhone = value; break;
                    default: break;
                }            
            }
        }
        public void PrintPhoneBook()
        {
            Console.WriteLine(name);
            Console.WriteLine("办公电话{0}",officePhone);
            Console.WriteLine("家庭电话{0}",homePhone);
            Console.WriteLine("私人电话{0}",mobilePhone);
        }
  
    }
}

<think>好的,我现在要解决用户关于C#索引使用方法和示例的问题。首先,我需要回忆一下C#索引的基本概念。根据引用[2],索引允许类像数组一样通过索引访问元素,这对于自定义集合类非常有用。用户需要具体的语法和示例,所以我得先整理索引的声明语法。 引用[4]中提到,声明索引的基本语法是使用this关键字,后跟参数和get、set访问。例如public string this[int index] { get { ... } set { ... } }。需要注意的是,索引只能用于实例成员,不能是静态的,这点在引用[1]里提到过。 接下来,我需要考虑如何给出一个清晰的示例。可能创建一个简单的类,比如StringList,内部用数组存储数据,然后通过索引访问。这样用户可以直观地看到如何实现get和set。此外,引用[3]指出索引可以有访问修饰符,并且get和set可以有不同的修饰符,但示例中可能先保持简单,使用public。 还要注意索引参数不仅可以是整数,也可以是其他类型,比如字符串。比如一个字典类可以用字符串作为键。这部分可以放在高级用法里,作为第二个示例,展示多类型参数的使用。 然后,用户可能想知道索引的实际应用场景,比如在集合类、数据封装或替代字典中的使用,根据引用[2]中的内容,这些都需要在相关问题和回答中提及。 最后,确保回答结构清晰,分点说明语法、示例和注意事项,并生成相关问题。检查引用的正确性,确保每个引用标识对应正确的来源。例如,引用[1]提到索引不能与this一起使用,但根据标准语法,索引正是使用this关键字,这里可能存在引用错误,需要确认。不过根据引用[4],正确语法是使用this,所以可能引用[1]的描述有误,或者用户引用有误,但作为回答者,应按照正确知识回答,可能引用[1]中的“不能与this关键字一起使用”是错误的,需要指出正确用法。</think>### C#索引使用方法及示例 #### 一、索引核心语法 索引允许类或结构体通过类似数组的语法访问成员,语法结构为: ```csharp public 返回类型 this[参数类型 参数名] { get { /* 返回值 */ } set { /* 设置值 */ } } ``` - 必须使用`this`关键字定义[^4] - 支持整型、字符串等多种参数类型[^2] - 可包含`get`和`set`访问(可设置不同访问权限)[^3] #### 二、基础使用示例 ```csharp public class StringList { private string[] _items = new string[10]; public string this[int index] { get => _items[index]; set => _items[index] = value; } } // 使用示例 var list = new StringList(); list[0] = "Hello"; // 通过索引赋值 Console.WriteLine(list[0]); // 输出:Hello ``` ▲ 实现类似数组的访问方式,封装内部数组操作 #### 三、高级应用示例 ```csharp public class TemperatureData { private float[] temps = new float[24]; // 多参数索引 public float this[int hour, TemperatureUnit unit] { get => unit == TemperatureUnit.Celsius ? temps[hour] : ConvertToFahrenheit(temps[hour]); set => temps[hour] = unit == TemperatureUnit.Celsius ? value : ConvertToCelsius(value); } } // 使用示例 var weather = new TemperatureData(); weather[12, TemperatureUnit.Fahrenheit] = 77.5f; ``` ▲ 支持多参数和单位转换的复合索引 #### 四、注意事项 1. 必须为实例成员,不能声明为`static`[^1] 2. 索引参数至少一个,不支持空参数[^3] 3. 可重载不同参数类型的索引[^4] 4. 访问可设置不同可见性: ```csharp public string this[int index] { internal get { ... } private set { ... } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值