【发布时间】:2011-09-15 18:40:42
【问题描述】:
我在翻别人的代码,看到了这样的说法:
public CustomClassName this [ string varName]
请原谅这个问题的新奇,但方括号让我失望。 这是方法还是构造函数?
“this”变量在这种情况下如何工作?
【问题讨论】:
标签: c# .net visual-studio-2010 c#-4.0
我在翻别人的代码,看到了这样的说法:
public CustomClassName this [ string varName]
请原谅这个问题的新奇,但方括号让我失望。 这是方法还是构造函数?
“this”变量在这种情况下如何工作?
【问题讨论】:
标签: c# .net visual-studio-2010 c#-4.0
它被称为索引器。 MSDN page.
【讨论】:
Default 更清晰:)
也不是,它是Indexer。它允许您执行 CustomClassName[ obj ] 并从对象中检索值。
【讨论】:
它是一个索引器,因此您可以访问类似于数组的类。
【讨论】:
它在你的类型上定义一个索引操作符。以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]; }
}
}
【讨论】:
【讨论】: