C#索引器Indexer
C#的索引器和C++中重写[]运算符的作用相同.
如果为类定义一个索引器, 就可以告诉编译器, 如果编译器遇到把类实例当作数组的代码, 该怎么办.
定义索引器的方式与定义属性的方式一样, 也使用get和set函数, 主要的区别是索引器的名称是关键字this, 要为Vector定义索引器, 就可以修改类的定义, 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic;
namespace CSharp_Text
{
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 override string ToString()
{
return "(" + x + "," + y + "," + z + ")";
}
public double this[int i]
{
get
{
switch (i)
{
case 0:
return x;
case 1:
return y;
case 2:
return 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);
}
}
}
}
class main
{
static void Main()
{
Vector vect1 = new Vector(1, -2, 4.1);
Vector vect2 = new Vector();
Console.WriteLine("vect1 = " + vect1);
Console.WriteLine("vect1[1] = " + vect1[1]);
for (int i = 0; i < 3; i++)
{
vect2[i] = i;
}
Console.WriteLine("vect2 = " + vect2);
}
}
}
using System.Linq;
using System.Text;
using Microsoft.VisualBasic;
namespace CSharp_Text
{
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 override string ToString()
{
return "(" + x + "," + y + "," + z + ")";
}
public double this[int i]
{
get
{
switch (i)
{
case 0:
return x;
case 1:
return y;
case 2:
return 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);
}
}
}
}
class main
{
static void Main()
{
Vector vect1 = new Vector(1, -2, 4.1);
Vector vect2 = new Vector();
Console.WriteLine("vect1 = " + vect1);
Console.WriteLine("vect1[1] = " + vect1[1]);
for (int i = 0; i < 3; i++)
{
vect2[i] = i;
}
Console.WriteLine("vect2 = " + vect2);
}
}
}
运行结果:
虽然可以用for, do和while循环来处理索引器, 但不能使用foreach循环. 因为foreach循环语句的工作方式不同, 它把元素当作一个集合, 而不是一个数组.
作者:Create Chen
出处:http://technology.cnblogs.com
说明:文章为作者平时里的思考和练习,可能有不当之处,请博客园的园友们多提宝贵意见。
本作品采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架