• c#编程指南(六) 类索引器(Class Indexer)


    类索引器,可以使得你使用数组一样的方式来访问类的数据。

    这种访问多见于数组,列表,词典,哈希表的快捷访问。

    实际上写法很简单,写成:public T1 this[T2 i]

    代码如下:

    using System;
     using System.Collections.Generic;
     using System.Linq;
     using System.Text;
     using System.Drawing;
    
     namespace Indexer
    {
        public class Test
        {
            private List<string> _lstTest = new List<string>();
    
            public List<string> Items 
            {
                get { return _lstTest; }
                set { _lstTest = value; }
            }
    
            public string this[int i]
            {
                get {
                    if ((i >= 0) && (i < _lstTest.Count)) return _lstTest[i];
                    else throw new IndexOutOfRangeException("the error index is " + i);
                }
    
                set {
                    if ((i >= 0) && (i < _lstTest.Count)) _lstTest[i] = value;
                    else throw new IndexOutOfRangeException("the error index is " + i);
                }
            }
    
            public string this[string s] { get { return "Test Return " + s; } }
    
    
            public string this[Color c] { get { return c.ToString(); } }
        }
    
    
        class Program
        {
            static void Main(string[] args)
            {
                Test test = new Test();
    
                test.Items.Add("test1");
                test.Items.Add("test2");
                test.Items.Add("test3");
                for (int i = 0; i < test.Items.Count; i++)
                {
                    Console.WriteLine(test[i]);
                }
    
                Console.WriteLine("----------------------------------------------------------");
                test[0] = "test4";
                for (int i = 0; i < test.Items.Count; i++)
                {
                    Console.WriteLine(test[i]);
                }
    
                Console.WriteLine("----------------------------------------------------------");
                Console.WriteLine(test["香山飘雪"]);
    
    
                Console.WriteLine("----------------------------------------------------------");
                Console.WriteLine(test[Color.BlueViolet]);
            }
        }
    }

    很简单吧,

    第一个,我定义了一个可读可写的以int为参数的索引器。

    第二个,我定义了一个可读的以string为参数的索引器。

    第三个,比较搞怪了,我定义了一个color参数的索引器。

  • 相关阅读:
    urlrewrite地址重写的使用
    算法学习
    数据库之Case When
    速卖通返回503错误
    概述:软件开发工具
    c#将List&lt;T&gt;转换成DataSet
    表单域规范写法
    ant打包和jar包混淆
    Node.js文档和教程
    webpack开发和生产两个环境的配置详解
  • 原文地址:https://www.cnblogs.com/xbzhu/p/7381394.html
Copyright © 2020-2023  润新知