【问题标题】:Can someone explain this C# syntax?有人可以解释这个 C# 语法吗?
【发布时间】:2016-07-07 18:50:29
【问题描述】:

这里实际发生了什么:

public decimal[] Coefficients;
public decimal this[int i]
{
    get { return Coefficients[i]; }
    set { Coefficients[i] = value; }
}

this 有什么作用?它是对decimal 的某种扩展吗?

【问题讨论】:

标签: c#


【解决方案1】:

这是一个Indexer

索引器允许类或结构的实例像数组一样被索引。索引器类似于属性,只是它们的访问器带有参数。

来自链接的 MSDN 的示例:

class SampleCollection<T>
{
    // Declare an array to store the data elements.
    private T[] arr = new T[100];

    // Define the indexer, which will allow client code
    // to use [] notation on the class instance itself.
    // (See line 2 of code in Main below.)        
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets
            // the corresponding element from the internal array.
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer.
class Program
{
    static void Main(string[] args)
    {
        // Declare an instance of the SampleCollection type.
        SampleCollection<string> stringCollection = new SampleCollection<string>();

        // Use [] notation on the type.
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}
// Output:
// Hello, World.

【讨论】:

    【解决方案2】:

    它是一个索引器,当您使用像 obj[1] 这样的语法时会调用它。 https://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

    【讨论】:

      【解决方案3】:

      你有没有想过 List&lt;T&gt;myList[i] 在 c# 中如何像数组一样工作?

      答案就在您的问题中。您发布的语法是一种语法糖,编译器会将其转换为名为@9​​87654324@ 和set_Item(int index, decimal value) 的属性。它用于List&lt;T&gt;,例如访问类中使用的内部数组并返回指定索引处的元素(设置或获取)。此功能称为Indexer

      要自己测试,请尝试创建具有相同签名的方法:

      public decimal get_Item(int i)
      {
           return 0;
      }
      

      你会得到一个编译器错误:

      错误 CS0082:类型“MyClass”已经保留了一个名为 'get_Item' 具有相同的参数类型

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-15
        相关资源
        最近更新 更多