【发布时间】:2017-01-04 08:52:44
【问题描述】:
如标题中所述,我不确定将结构视为数组时调用的特定功能。例如,Unity3D 有 Color 结构,它有 4 个公共浮点数 r,g,b,a 和 public float this[int index] { get;放; }。这个功能有什么特殊的术语吗?我来自 Java,刚开始学习 C#,我试图查找这是什么,但只是找到有关如何创建结构数组的内容。
【问题讨论】:
如标题中所述,我不确定将结构视为数组时调用的特定功能。例如,Unity3D 有 Color 结构,它有 4 个公共浮点数 r,g,b,a 和 public float this[int index] { get;放; }。这个功能有什么特殊的术语吗?我来自 Java,刚开始学习 C#,我试图查找这是什么,但只是找到有关如何创建结构数组的内容。
【问题讨论】:
例子:
public struct Color
{
public int R { get; }
public int G { get; }
public int B { get; }
public int this[int index]
{
get
{
switch(index)
{
case 0: return R;
case 1: return G;
case 2: return B;
}
throw new IndexOutOfRangeException();
}
}
}
(注意:不是你使用的真正的Color,只是我脑海中的一个例子)
【讨论】:
这样的属性称为indexer:
public struct Color
private float[] components;
public float this[int index] { //<-- indexer.
get {
if (components == null) {
components = new float[4];
}
return components[index];
}
set {
if (components == null) {
components = new float[4];
}
components[index] = value;
}
}
}
【讨论】: