C#索引符[索引器]

索引符或叫索引器,是将类或结构的实例转为数租,按数组的方式设置和获取元素值 。索引符可以看做[]运算符的重载。
索引符常用于表示某些数据结构的类、数组、列表和映射等,并可以在.Net基类中定义这些结构体。也可用于引用类型的转换。
索引符和数组比较:
(1)索引符的索引值(Index)类型不受限制
(2)索引符允许重载
(3)索引符不是一个变量
索引符和属性的不同点
(1)属性以名称来标识,索引符以函数形式标识
(2)索引符可以被重载,属性不可以
(3)索引符不能声明为static,属性可以。

using System;
struct Vector
{
 public double x,y,z;
  public Vector(double x,double y,double z)
 {
  this.x = x;
  this.y = y;
  this.z = z;
 }
 
 public Vector(Vector rhs)
 {
  x = rhs.x;
  y = rhs.y;
  z = rhs.z;
 }
 
 //继承Object的Tostring()
 public override string ToString()
 {
  return"("+x+","+y+","+z+")";
 }
 
//定义索引
 public double this[int i]
 {
  get
  {
   switch(i)
   {
    case 0:
     return this.x;
    case 1:
     return this.y;
    case 2:
     return this.z;
    default:
     throw new IndexOutOfRangeException("Attempt to retrieve Vector element"+i);
   }
  }
  set
  {
   switch(i)
   {
    case 0:
     x = value;
     break;
    case 1:
     y = value;
     break;
    case 2:
     z = value;
     break;
    default:
     throw new IndexOutOfRangeException("Attempt to set Vector element"+i);
   }
   
  }
 }
 
 public static void Main()
  {
   Vector Vect1 = new Vector(1.0,-5.0,4.6);
   Vector Vect2 = new Vector();
   Console.WriteLine("Vect1 = "+Vect1);
   Console.WriteLine("Vect[i] = "+Vect1[0]);  //使用数组下标获取元素
   
   for(int i=0;i<3;i++)
   {
    Vect2[i] = i;
   }
   Console.WriteLine("Vect2 = "+Vect2);
   Console.WriteLine("Vect2 = "+Vect2[2]);
  }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值