【问题标题】:Basic C# class question regarding the "this" keyword关于“this”关键字的基本 C# 类问题
【发布时间】:2011-09-15 18:40:42
【问题描述】:

我在翻别人的代码,看到了这样的说法:

public CustomClassName this [ string varName]

请原谅这个问题的新奇,但方括号让我失望。 这是方法还是构造函数?

“this”变量在这种情况下如何工作?

【问题讨论】:

    标签: c# .net visual-studio-2010 c#-4.0


    【解决方案1】:

    它被称为索引器。 MSDN page.

    【讨论】:

    • 原来如此! VB.NET 的Default 更清晰:)
    • @minitech:值得商榷。我在 VB 中没有遇到过一个我认为比 C# 寓言更清晰的构造。
    【解决方案2】:

    也不是,它是Indexer。它允许您执行 CustomClassName[ obj ] 并从对象中检索值。

    【讨论】:

      【解决方案3】:

      它是一个索引器,因此您可以访问类似于数组的类。

      【讨论】:

        【解决方案4】:

        它在你的类型上定义一个索引操作符。以List<T> 类为例。库设计者希望您能够编写如下代码:

        List<int> list = new List<int> { 1, 2, 3, 4, 5 };
        int x = list[2]; // x == 3
        

        实现这一点的语法就是您在上面发布的内容。因此,对于您自己的类型,您可以...

        class NameCollection : /* whatever */
        {
            private List<string> _names = new List<string> { "Ed", "Sally", "John" };
        
            public string this[int index]
            {
                get { return _names[index]; }
            }
        }
        

        【讨论】:

          【解决方案5】:

          这只是 C# 中方括号运算符的重载。

          看这里:

          How do I overload the square-bracket operator in C#?

          【讨论】:

            猜你喜欢
            • 2021-10-30
            • 2011-12-11
            • 1970-01-01
            • 2018-10-12
            • 2011-02-01
            • 2016-06-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多