H_J_H

------专用杂物房
posts - 26, comments - 1, trackbacks - 0, articles - 119

[导入]索引器

Posted on 2006-04-26 21:17 H_J_H 阅读(59) 评论(0)  编辑 收藏 引用
 C#通过提供索引器(indexer),使得用户可以像处理数组一样对对象使用下标。索引器为我们提供了通过索引方式访问类的数据的方法。
例:
using System;

namespace suoyinqi

{

    class Vector

    {

        private double x,y,z;

        public double this[int i]//定义索引器,使得可以使用数组的方式访问Vector的数据

        {

            get

            {

                switch(i)

                {

                    case 0:

                        return x;

                    case 1:

                        return y;

                    case 2:

                        return z;

                    default:

                        throw new IndexOutOfRangeException("访问下标超出范围!");//若访问下标超出范围,抛出异常

                }

            }

            set

            {

                switch(i)

                {

                    case 0:

                        x = value;

                        break;

                    case 1:

                        y = value;

                        break;

                    case 2:

                        z = value;

                        break;

                    default:

                        throw new IndexOutOfRangeException("访问下标超出范围!");//若访问下标超出范围,抛出异常

                }

            }

        }

    }

    public class Class1

    {

        [STAThread]

        public static void Main(string[] args)

        {

            Vector v = new Vector();

            v[0] = 4;

            v[1] = 5;

            v[2] = 6;

            Console.WriteLine("Vector.x = {0}",v[0]);

            Console.WriteLine("Vector.y = {0}",v[1]);

            Console.WriteLine("Vector.z = {0}",v[2]);

        }

    }

}



sopper 2006-04-13 16:38

文章来源:http://sopper.cnblogs.com/archive/2006/04/13/374410.html
只有注册用户登录后才能发表评论。