C#中索引器简单使用

微软官方描述:索引器允许类或结构的实例就像数组一样进行索引。索引器形态类似于,不同之处在于它们的取值函数采用参数。
通俗理解:索引器(Indexer) 允许一个对象可以像数组一样被索引。当您为类定义一个索引器时,该类的行为就会像一个 虚拟数组(virtual array) 一样。您可以使用数组访问运算符([ ])来访问该类的实例。
索引的代码结构接近与类的属性定义,都是通过get和set来进行相关业务操作,只是比属性多了签名,索引允许重载,索引支持多种数据类,可以通过对象+【签名】来调用该索引

索引结构:

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

   // set 访问器
   set 
   {
      // 设置 index 指定的值 
   }
}

索引简单使用:

public class Indexer {

        public static int size = 10;
        private string[] array = new string[size];
        public Indexer() {
            for (int i= 0;i < 10;i++) {
                array[i] = "N/A";
            }
        }
        /// <summary>
        /// 给属性设置或获取属性值
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public string this[int i] {
            get {
                if (i < 0 || i >= size) {
                    return "";
                }
                else {
                    return array[i];
                }
            }
            set {
                if (i < 0 || i >= size) {

                }
                else {
                     array[i]=value;
                }
            }
        }
        /// <summary>
        /// 查看当前属性的值是否等于传过来的值
        /// </summary>
        /// <param name="i"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool this[int i, string value] {
            get {
                if (i < 0 || i >= size) {
                    return false;
                }
                else {
                    if (array[i].Equals(value)) return true;
                    else return false; 
                }
            }
        }
    }

调用:

#region Indexer
            Indexer index = new Indexer();
            index[0] = "Zara";
            index[1] = "Riz";
            index[2] = "Nuha";
            index[3] = "Asif";
            index[4] = "Davinder";
            index[5] = "Sunil";
            index[6] = "Rubic";
            index[7] = "Rubic11";
            index[8] = "Rubic22";
            index[9] = "Rubic33";
            for (int i = 0; i < Indexer.size; i++) {
                Console.WriteLine(index[i]);
            }
            Console.WriteLine(index[1, "Riz"]);
            Console.ReadKey();
            #endregion

可以参考的例子:

namespace Study
{
    class Program
    {
        static void Main(string[] args)
        {
            ScoreIndex s = new ScoreIndex();
            s["张三", 1] = 90;
            s["张三", 2] = 100;
            s["张三", 3] = 80;
            s["李四", 1] = 60;
            s["李四", 2] = 70;
            s["李四", 3] = 50;
            Console.WriteLine("张三课程编号为1的成绩为:" + s["张三",1]);
            Console.WriteLine("张三的所有成绩为:");
            ArrayList temp;
            temp = s["张三"];
            foreach (IndexClass b in temp) 
            {
                Console.WriteLine("姓名:" + b.Name + "课程编号:" + b.CourseID + "分数:" + b.Score);
            }
            Console.ReadKey();
        }
    }
    class IndexClass 
    {
        private string _name;
        private int _courseid;
        private int _score;
        public IndexClass(string _name, int _courseid, int _score) 
        {
            this._name = _name;
            this._courseid = _courseid;
            this._score = _score;
        }
        public string Name 
        {
            get { return _name; }
            set { this._name = value; }
        }
        public int CourseID 
        {
            get { return _courseid; }
            set { this._courseid = value; }
        }
        public int Score 
        {
            get { return _score; }
            set { this._score = value; }
        }
    }
    class ScoreIndex 
    {
        private ArrayList arr;
        public ScoreIndex() 
        {
            arr = new ArrayList();
        }
        public int this[string _name, int _courseid] 
        {
            get 
            {
                foreach (IndexClass a in arr) 
                {
                    if (a.Name == _name && a.CourseID == _courseid) 
                    {
                        return a.Score;
                    }
                }
                return -1;
            }
            set 
            {
                arr.Add(new IndexClass(_name, _courseid, value)); //arr["张三",1]=90
            }
        }
        //重载索引器
        public ArrayList this[string _name] 
        {
            get 
            {
                ArrayList temp = new ArrayList();
                foreach (IndexClass b in arr) 
                {
                    if (b.Name == _name) 
                    {
                        temp.Add(b);
                    }
                }
                return temp;
            }
        }
    }
}
<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、付费专栏及课程。

余额充值