c# - C# 中索引器和属性之间有什么关系?

标签 c# properties indexer

索引器是属性的扩展版本吗?

最佳答案

索引器允许像数组一样对类或结构的实例进行索引。索引器类似于属性,只不过它们的访问器采用参数。

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]);
    }
}

http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

关于c# - C# 中索引器和属性之间有什么关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1768711/

相关文章:

c# - f# 控制台应用程序不工作。 c# 控制台应用程序确实

tomcat - web.xml:从属性文件设置值

Eclipse Indexer 中的 C++11 设置与 git 冲突

c# - 如何在索引器类上使用 DebuggerDisplay 属性

c# - bootStrap 菜单添加的元素无法访问后面的 asp.net 代码

c# - Mapster - 如何忽略空属性的映射

java - 当并非所有属性都在同一个类中时填充 JavaFX TableView

sql全文搜索不搜索确切的短语

c# - Visual Studio 2008 Extension 快速测试功能? C#

ant - 如何对属性的位置属性使用 glob 模式?