zoukankan      html  css  js  c++  java
  • C#2008与.NET 3.5 高级程序设计读书笔记(12) 索引器

    1.索引器

    (1)定义:它使对象能够用与数组相同的方式进行索引.以这种方式访问子项的方法称为索引器方法.构建自定义集合类型时,这个特殊的语言功能特别有用

    类似于属性,都是通过访问器进行数据访问的.属性是对字段的封装,而索引器是对"集合、数组..."进行封装.

    例子:

    代码
    namespace TestDemo
    {
    class Program
    {
    static void Main(string[] args)
    {
    PeopleCollection collection
    = new PeopleCollection();
    //存取值类似数组的方式
    collection[0] = new Person("Engine", 26);
    collection[
    1] = new Person("Arvin", 30);
    Console.WriteLine(collection[
    0].name);
    }
    }
    public class PeopleCollection
    {
    ArrayList arrPeople
    = new ArrayList();
    //定义索引器,对子项(数组或集合)的封装
    public Person this[int index]
    {
    get
    {
    return (Person)arrPeople[index];
    }
    set
    {
    arrPeople.Insert(index, value);
    }
    }
    }
    public class Person
    {
    public int age;
    public string name;
    public Person(string name, int age)
    {
    this.name = name;
    this.age = age;
    }
    }

    索引在构建自定义集合索引器方法很常见,但是需要记住,泛型直接支持这个功能

    代码
    namespace TestDemo
    {
    class Program
    {
    static void Main(string[] args)
    {
    List
    <Person> personList = new List<Person>();
    personList.Add(
    new Person("Engine", 26));
    personList.Add(
    new Person("Arvin", 30));
    Console.WriteLine(personList[
    0].name);
    }
    }
    public class Person
    {
    public int age;
    public string name;
    public Person(string name, int age)
    {
    this.name = name;
    this.age = age;
    }
    }

    }

    在接口类型上定义索引器

    代码
    public interface IStringContainer
    {
    //这个接口定义了一个基于数组索引返回字符串的索引器
    string this[int index]{get;set;}
    }
    public class MyString : IStringContainer
    {
    string[] strings = { "Frist", "Second" };
    #region IStringContainer Members

    public string this[int index]
    {
    get
    {
    return strings[index];
    }
    set
    {
    strings[index]
    = value;
    }
    }

    #endregion
    }
  • 相关阅读:
    springboot+mybatisplus使用xml找不到mapper的解决办法
    PDF转换成Word文档
    Mybatis-Plus增删改查
    Redis 常用命令
    Java 获取两个List<String>中不同的数据
    controller 返回界面 中文乱码
    Navicat已经成功连接,密码忘记的解决方案
    List数组指定切割
    xml字符串转换成Map
    Java 前一个月的最后一天日期计算
  • 原文地址:https://www.cnblogs.com/engine1984/p/1782278.html
Copyright © 2011-2022 走看看