【问题标题】:C# Struct feature - Color[(int)channel]C# 结构特征 - 颜色[(int)channel]
【发布时间】:2017-01-04 08:52:44
【问题描述】:

如标题中所述,我不确定将结构视为数组时调用的特定功能。例如,Unity3D 有 Color 结构,它有 4 个公共浮点数 r,g,b,a 和 public float this[int index] { get;放; }。这个功能有什么特殊的术语吗?我来自 Java,刚开始学习 C#,我试图查找这是什么,但只是找到有关如何创建结构数组的内容。

【问题讨论】:

    标签: c# arrays struct


    【解决方案1】:

    它被称为"indexer property"

    例子:

    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,只是我脑海中的一个例子)

    【讨论】:

    • 谢谢!绝对是来自 Java 的我不熟悉的东西。
    【解决方案2】:

    这样的属性称为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;
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      显然,Unity3D 的开发人员有时想要访问Color,就好像它是 ARGB(又名通道)值的集合一样。他们使用 indexer 操作符 来模仿它。

      您可以在 MSDN herehere 上阅读有关索引器运算符的更多信息。

      【讨论】:

        猜你喜欢
        • 2016-05-13
        • 1970-01-01
        • 2013-12-21
        • 2020-04-05
        • 2012-08-15
        • 2012-06-27
        • 2020-05-16
        • 1970-01-01
        • 2019-02-08
        相关资源
        最近更新 更多