• 步步为营-06-索引器


    索引器-经常用,但不常写,仅作为知识点了解一下

    1:定义Person类,类中定义一个数组字段

    2:为了方便外部访问,封装为属性

      int[] numbers = new int[5];

      public int[] Numbers         {       

          get { return numbers; }            

       set { numbers = value; }       

      }

    3:外部访问

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Indexer
    {
        class Program
        {
            static void Main(string[] args)
            {
                Person p = new Person();
                p.Numbers = new int[] {1,2,2,3,8,5};
                foreach (var item in p.Numbers)
                {
                    Console.WriteLine(item);
                }
                Console.Read();
            }
        }
    }
    View Code

    现在想不通过属性直接索引器访问.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Indexer
    {
        class Program
        {
            static void Main(string[] args)
            {
                Person p = new Person();
                //p.Numbers = new int[] {1,2,2,3,8,5};
                //foreach (var item in p.Numbers)
                //{
                //    Console.WriteLine(item);
                //}
                p[0] = 1;
                p[4] = 5;
                for (int i = 0; i < 5; i++)
                {
                    Console.WriteLine(p[i]);
                }
                Console.Read();
            }
        }
    }
    View Code

    4:进一步介绍索引器的重载,通过字典

     Dictionary< string,int> dic = new Dictionary< string,int>();
            public  int this[string index]
            {
                set { dic[index] = value; }
                get { return dic[index]; }
            }

    在main方法中调用

     p["张三"] = 1;
    Console.WriteLine(p["张三"]);

  • 相关阅读:
    [转][c#]C# 二维数组到底该如何定义?
    [c++]筛法求素数
    USB驱动问题
    使用Ajax.dll前台调用后台方法及错误示例
    asp.net中前台javascript与后台C#交互
    visual stdio2010 生成的缓存文件
    jQuery.ajax概述[转]
    一种正向最小匹配的中文分词算法
    2010 .NET面试题整理之基础篇[转]
    Winform设计不规则窗体
  • 原文地址:https://www.cnblogs.com/YK2012/p/6705004.html
Copyright © 2020-2023  润新知