作为属性的'this'关键字
问题描述:
我很熟悉C#,但这对我来说很奇怪。在一些旧程序中,我看到了这样的代码:作为属性的'this'关键字
public MyType this[string name]
{
......some code that finally return instance of MyType
}
它是如何调用的?这有什么用处?
答
它是indexer。宣布后,您可以这样做:
class MyClass
{
Dictionary<string, MyType> collection;
public MyType this[string name]
{
get { return collection[name]; }
set { collection[name] = value; }
}
}
// Getting data from indexer.
MyClass myClass = ...
MyType myType = myClass["myKey"];
// Setting data with indexer.
MyType anotherMyType = ...
myClass["myAnotherKey"] = anotherMyType;
答
这是一个Indexer Property。它允许你通过索引直接“访问”你的类,就像访问数组,列表或字典一样。
在你的情况,你可以有这样的:
public class MyTypes
{
public MyType this[string name]
{
get {
switch(name) {
case "Type1":
return new MyType("Type1");
case "Type2":
return new MySubType();
// ...
}
}
}
}
那么你可以使用此类似:
MyTypes myTypes = new MyTypes();
MyType type = myTypes["Type1"];
答
这是一个特殊的属性,称为索引器。这可以让你的类像数组一样被访问。
myInstance[0] = val;
你会在自定义集合最经常看到这种行为,作为数组的语法是一个众所周知的接口,用于访问可以通过一个键值来识别一个集合,通常它们的位置中的元素(如数组和列表)或逻辑密钥(如在字典和散列表中)。
您可以在MSDN文章Indexers (C# Programming Guide)中找到更多关于索引器的内容。
如果您在“.... some code”块中显示属性获取(和/或设置)访问器,此答案会更完整。这表明它更像是一种方法。 – 2010-03-25 16:36:17
谢谢,我已经更新了答案。 – 2010-03-25 16:38:01
通过构建覆盖大多数人的需求的通用集合,使得它们变得非常不常见。不需要编写自己的强类型集合来获得标准行为了。 – 2010-03-25 17:01:05