C#索引器的应用:自已写一个表格

C#中索引器,在一个类中有很多的同一类型成员的时候,比较适用索引器。

环境:我们假设有一个动物园,里边有很多动物。

用法:

1.先定义一个类,这是成员的类型。在这里就是要定义一个Animal类;

public class Animal
    {
        public string Name { get; set; }
    }


2.再定义一个包含索引器的类,在这里是Zoo动物园类。

public class Zoo
    {
        private List<Animal> animals = new List<Animal>();
        public Animal this[int index]
        {
            get{return animals[index];}
            set{animals.Add(value);}
        }
    }


3.那么我们在主程序里就可以这么用:

class Program
    {
        static void Main(string[] args)
        {
            Animal a = new Animal();
            a.Name = "老虎";
            Animal b = new Animal();
            b.Name = "大象";

            Zoo z=new Zoo();
            z[0] = a;
            z[1] = b;

            Console.WriteLine(z[0].Name);

            Animal c;
            c = z[1];
            Console.WriteLine(c.Name);
        }
    }


好了,接下来,我们来自定义一个我们自己的表格:

1.先定义Cell单元格类

class Cell
    {
        public string Text { get; set; }
    }

2.定义Row行 类(注意在这里我们必须就得用List<Cell>了。因为它包含很多Cell成员了,下边的Table也是,包含很多row)

class Row
    {
        private List<Cell> cells = new List<Cell>();
        public Cell this[int index]
        {
            get { return cells[index]; }
            set { cells.Add(value); }
        }
    }


3.再定义Table 表格类

   

    class Table
    {
        private List<Row> rows = new List<Row>();
        public Row this[int index]
        {
            get { return rows[index]; }
            set { rows.Add(value); }
        }
    }

4.最后我们在主程序里可以用了:

class Program
    {
        static void Main(string[] args)
        {
            Cell c0= new Cell();
            c0.Text = "姓名";
            Cell c1 = new Cell();
            c1.Text = "性别";
            
            Cell c2=new Cell();
            c2.Text="张三";
            Cell c3=new Cell();
            c3.Text="男";

            Row row = new Row();
            row[0] = c0;
            row[1] = c1;
            Row row2 = new Row();
            row2[0] = c2;
            row2[1] = c3;

            Table table = new Table();
            table[0] = row;
            table[1] = row2;
            //取得表格第0行,第1列的单元格内容
            //Console.WriteLine(table[0][1].Text);
            //取得表格第1行,第0列的单元格内容
            //Console.WriteLine(table[1][0].Text);

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    Console.Write(table[i][j].Text+" ");
                }
                Console.WriteLine();
            }


输出结果:


原文地址:https://www.cnblogs.com/riskyer/p/3289771.html