Home
03 索引器
Unity
03 索引器
姜睿
姜睿
August 18, 2022
1 min

Table Of Contents

01
声明、定义、赋值、读取
02
索引器重载
03
访问修饰符

声明、定义、赋值、读取

  • 索引器可以为类的多个数据成员提供 getset 访问器。

例 1

1
2internal class Player
3{
4private int health = 2;
5private int shield = 4;
6private int attack = 8;
7
8public Player(int health = 2, int shield = 4, int attack = 8)
9{
10this.health = health;
11this.shield = shield;
12this.attack = attack;
13}
14
15// ReturnType this [ Type param1 ...] { get {..} set {...} }
16public int this[int index]
17{
18get
19{
20switch (index)
21{
22case 0: return health;
23case 1: return shield;
24case 2: return attack;
25default: throw new IndexOutOfRangeException();
26}
27}
28
29set
30{
31switch (index)
32{
33case 0: health = value; break;
34case 1: shield = value; break;
35case 2: attack = value; break;
36default: throw new IndexOutOfRangeException();
37}
38}
39}
40}
41
42internal class Program
43{
44private static void Main(string[] args)
45{
46Player player = new Player();
47// modify
48player[0] = 4;  // health = 4;
49player[1] = 8;  // shield = 8;
50player[2] = 16; // attack = 16;
51player[3] = 16; // Index was outside the bounds of the array.
52
53// read
54Console.WriteLine($"Health: {player[0]}, " + 
55$"Shield: {player[1]}, Attack: {player[2]}"
56}
57}
58

例 2

1
2internal class TransformRecord
3{
4// float[,] array = new float[3, 2]
5float[][] records = new float[3][]
6{
7new float[2] { 1, 1 },
8new float[2] { 2, 2 },
9new float[2] { 3, 3 }
10};
11
12public float[] this[int index]
13{
14get { return records[index]; }
15set { records[index] = value; }
16}
17
18public TransformRecord() { }
19}
20
21internal class Program
22{
23private static void Main(string[] args)
24{
25TransformRecord transformRecord = new TransformRecord();
26Console.WriteLine($"x: {transformRecord[0][0]}, " +
27$"y: {transformRecord[0][1]}"); ;
28// Output: x: 1, y: 1
29}
30}
31
32

索引器重载

  • 索引器的重载必须有不同的参数列表。
1
2internal class Example
3{
4// fields
5int[] array_1 = new int[2];
6float[] array_2 = new float[2];
7string[] array_3 = new string[] { "str1", "str2" };
8
9public int this[int index]
10{
11get { return array_1[index]; }
12}
13public float this[float index]
14{
15get { return array_2[(int)index]; }
16}
17public string this[string index]
18{
19get { return array_3[Int32.Parse(index)]; }
20}
21}
22

访问修饰符

  • 仅当属性/索引器既有 get 也有 set 访问器时,才能有访问修饰符。
  • 有且只有一个访问修饰符。
  • 访问器的访问修饰符应该比属性/索引器的访问级别更加严格。
    • public > protected internal > protected & internal > private
    • 例如:一个索引器的访问级别为 public ,那么它的访问器的级别为任意。

Tags

#game developc#
姜睿

姜睿

学生

游戏设计学生

Expertise

游戏开发
平面设计

Related Posts

策略模式
策略模式
November 19, 2023
1 min

Legal Stuff

Privacy NoticeCookie PolicyTerms Of Use