C# 类 索引器 概念
2021-01-25 15:12
标签:except sys width ati pac row namespace vat ogr 将实例对象中的不同字段分别映射到不同的下标,通过类似数组的方式访问对象,和属性一样可以 C# 类 索引器 概念 标签:except sys width ati pac row namespace vat ogr 原文地址:https://www.cnblogs.com/esrevinud/p/12014094.html类索引器
get/set
using System;
namespace Hello
{
class Shape
{
private int _width;
private int _height;
public int this[int index]
{
set
{
// 指定下标对应的字段
switch (index)
{
case 0:
this._width = value;
break;
case 1:
this._height = value;
break;
}
}
get
{
switch (index)
{
case 0:
return this._width;
case 1:
return this._height;
default:
throw new IndexOutOfRangeException("不存在该下标对应的字段");
}
}
}
}
public class Program
{
public static void Main()
{
Shape shape = new Shape();
// 此时shape中的字段分别对应不同的下标,超出则会报错
shape[0] = 12;
shape[1] = 20;
Console.WriteLine("width = {0}, height = {1}", shape[0], shape[1]);
}
}
}