• .NET基础知识之七——索引器


           索引器是什么?有什么作用?索引器允许类的实例以访问数组的形式来访问对象里面的属性。如我们经常可以看到类似于dr[“name”]=”test”,或者说以config[“connectString”]来获取连接字符串的值。这都是使用索引器的例子,那么我们如何在自己的类中来定义索引器呢?

            索引器的简单使用

           其实索引器的定义非常简单,只需要使用this关键字即可。This关键字表示的是当前实例化的对象,所以通过这点,就知道索引器不能是静态的,它只能是实例化后才能使用。看下面的例子:

       1: public class People:IAnimal
       2:     {
       3:         private string strName;
       4:  
       5:         public string StrName
       6:         {
       7:             get { return strName; }
       8:             set { strName = value; }
       9:         }
      10:  
      11:         private string strNo;
      12:  
      13:         public string StrNo
      14:         {
      15:             get { return strNo; }
      16:             set { strNo = value; }
      17:         }
      18:  
      19:  
      20:         public string this[int a]
      21:         {
      22:             get
      23:             {
      24:                 if (a == 0)
      25:                 {
      26:                     return this.strName;
      27:                 }
      28:                 else
      29:                 {
      30:                     return this.strNo;
      31:                 }
      32:             }
      33:  
      34:             set
      35:             {
      36:                 if (a == 0)
      37:                 {
      38:                     this.strName = value;
      39:                 }
      40:                 else
      41:                 {
      42:                     this.strNo = value;
      43:                 }
      44:             }
      45:         }
      46:  
      47: }

            这就定义了一个参数为int类型的索引器,然后你在代码里面就可以通过数组的形式来给这个对象里面的属性赋值,也可以通过这种形式来读取这个对象的属性。

       1: static void Main(string[] args)
       2:        {
       3:            People p = new People();
       4:            p.StrName = "zhangsan";
       5:            p.StrNo = "11111";
       6:            //p[0] = "zhangsan";
       7:            //p[1] = "11111";
       8:  
       9:            Console.WriteLine("索引器" + p[0] + ";直接读取属性值:" + p.StrName);
      10:            Console.WriteLine("索引器" + p[1] + ";直接读取属性值:" + p.StrNo);
      11:            Console.ReadLine();
      12:         }

    也可以定义一个参数为String的索引器,那么在索引的时候,就可以输入一个字符串,然后通过数组的形式来访问某个对象的属性。如:

       1: public string this[string str]
       2:         {
       3:             get
       4:             {
       5:                 if (str == "name")
       6:                 {
       7:                     return this.strName;
       8:                 }
       9:                 if (str == "no")
      10:                 {
      11:                     return this.strNo;
      12:                 }
      13:  
      14:                 throw new Exception("未找到对应的属性");
      15:             }
      16:  
      17:             set
      18:             {
      19:                 if (str == "name")
      20:                 {
      21:                     this.strName = value;
      22:                     return;
      23:                 }
      24:                 if (str == "no")
      25:                 {
      26:                     this.strNo = value;
      27:                     return;
      28:                 }
      29:  
      30:                 throw new Exception("未找到对应的属性");
      31:  
      32:             }
      33:         }

    在接口中定义索引器

    索引器是可以在接口中进行定义的,定义的形式如下:

       1: interface IAnimal
       2:    {
       3:         void Say();
       4:        //注意此处需要写上get,set而且后面还不能有分号
       5:         string this[string str]{get;set;}
       6:    }

    调用及实现的时候,就跟调用和实现普通的方法是差不多的。

    索引器的应用(读取配置文件)

    定义一个Xml文件如下,读取里面的配置信息:

       1: <?xml version="1.0" encoding="utf-8" ?>
       2:   <connectstring >
       3:     <name key="db1" value="Database=test1111,userId=zhangsan,password=123;">
       4:     </name>
       5:     <name key="db2" value="Database=test2222,userId=lisi,password=123;">
       6:     </name>
       7:   </connectstring>

    封装一个类,在这个类里面读取相应的Xml文件信息,并且定义一个索引器,到时候通过Xml文件中key的值来得到相应的数据库连接字符串:

       1: public class ConfigClass
       2:     {
       3:         public ConfigClass()
       4:         {
       5:             ReadFile();
       6:         }
       7:         private XmlDocument xmlDoc;
       8:         private XmlNode xmlNode;
       9:  
      10:         public void ReadFile()
      11:         {
      12:             string path = @"....MyConfigure.xml";
      13:             this.xmlDoc = new XmlDocument();
      14:             this.xmlDoc.Load(path);
      15:             xmlNode = this.xmlDoc.SelectSingleNode(@"connectstring");
      16:  
      17:         }
      18:         private string conStr;
      19:  
      20:         public string ConStr
      21:         {
      22:             get { return conStr; }
      23:             set { conStr = value; }
      24:         }
      25:  
      26:         public string this[string str]
      27:         {
      28:             get
      29:             {
      30:                 XmlNodeList nodelist = xmlNode.ChildNodes;
      31:                 foreach (XmlElement xE in nodelist)
      32:                 {
      33:                     if (xE.Name == "name" && xE.GetAttribute("key")==str)
      34:                     {
      35:                         return xE.GetAttribute("value");
      36:                     }
      37:                 }
      38:  
      39:                 return "";
      40:  
      41:             }
      42:            
      43:         }

    此例子纯属演示,所以很多细节也没注意,只要知道这个意思即可.前台调用如下:

       1: ConfigClass cofig = new ConfigClass();
       2:  
       3: Console.WriteLine(cofig["db1"]);
       4: Console.WriteLine(cofig["db2"]);
       5: Console.ReadLine();

    运行结果情况如下:

    image

    参考:

    http://www.cnblogs.com/lengbingshy/archive/2010/02/23/1671912.html
    http://www.cnblogs.com/aspnethot/articles/1386650.html
    http://www.cnblogs.com/ArmyShen/archive/2012/08/27/2659405.html

  • 相关阅读:
    初识python 2.x与3.x 区别
    装饰器
    函数的进阶
    Spring Boot启动问题:Cannot determine embedded database driver class for database type NONE
    22.Spring Cloud Config安全保护
    23.Spring Cloud Bus 无法更新问题(踩坑) Spring cloud config server Could not fetch remote for master remote
    24.Spring Cloud之Spring Cloud Config及Spring Cloud Bus
    Spring Boot整合Spring Data Elasticsearch 踩坑
    项目中Spring Security 整合Spring Session实现记住我功能
    32.再谈SpringBoot文件上传
  • 原文地址:https://www.cnblogs.com/xiaoxiangfeizi/p/3455028.html
Copyright © 2020-2023  润新知