【问题标题】:How do I overload the [] operator in C# [duplicate]如何在 C# 中重载 [] 运算符 [重复]
【发布时间】:2010-09-30 07:03:40
【问题描述】:

我想给一个类添加一个运算符。我目前有一个 GetValue() 方法,我想用 [] 运算符替换它。

class A
{
    private List<int> values = new List<int>();

    public int GetValue(int index) => values[index];
}

【问题讨论】:

    标签: c# operator-overloading indexer


    【解决方案1】:
    public int this[int key]
    {
        get => GetValue(key);
        set => SetValue(key, value);
    }
    

    【讨论】:

    • 为什么每次我需要实现一个索引操作符的时候,我都要查一下?每次我最终得到这个答案......希望我能多次投票:)
    • 这太棒了。可以在界面中完成吗? interface ICache { object this[string key] { get; set; } } 编辑: Yes.
    • 不知道他们为什么选择在这个声明中省略“操作员”这个词——这就是我经常犯的错误!不错的答案
    • Michael:你可能应该使用泛型:interface ICache&lt;TContent&gt; { TContent this[string key] { get; set; } }
    • 我只是想和自己打个招呼,以后他一定会回来的
    【解决方案2】:

    我相信这就是您正在寻找的:

    Indexers (C# Programming Guide)

    class SampleCollection<T>
    {
        private T[] arr = new T[100];
        public T this[int i]
        {
            get => arr[i];
            set => arr[i] = value;
        }
    }
    
    // This class shows how client code uses the indexer
    class Program
    {
        static void Main(string[] args)
        {
            SampleCollection<string> stringCollection = 
                new SampleCollection<string>();
            stringCollection[0] = "Hello, World";
            System.Console.WriteLine(stringCollection[0]);
        }
    }
    

    【讨论】:

      【解决方案3】:

      [] 运算符称为索引器。您可以提供采用整数、字符串或您想用作键的任何其他类型的索引器。语法很简单,遵循与属性访问器相同的原则。

      例如,在您的情况下,int 是键或索引:

      public int this[int index]
      {
          get => GetValue(index);
      }
      

      您还可以添加一个 set 访问器,使索引器变为可读写,而不仅仅是只读。

      public int this[int index]
      {
          get => GetValue(index);
          set => SetValue(index, value);
      }
      

      如果您想使用不同的类型进行索引,只需更改索引器的签名即可。

      public int this[string index]
      ...
      

      【讨论】:

      • 别忘了你可以有多个索引器的任何类型组合......
      【解决方案4】:
      public int this[int index]
      {
          get => values[index];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-27
        • 2012-12-22
        • 2016-09-26
        • 2012-04-21
        • 1970-01-01
        • 1970-01-01
        • 2020-04-29
        相关资源
        最近更新 更多