‘this’关键字作为属性

我很了解C#,但这对我来说很奇怪。 在一些旧程序中,我看到了这段代码:

public MyType this[string name] { ......some code that finally return instance of MyType } 

怎么称呼? 有什么用?

它是索引器 。 声明之后你可以这样做:

 class MyClass { Dictionary 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"]; 

这是一个名为Indexer的特殊属性。 这允许您的类像数组一样被访问。

 myInstance[0] = val; 

您最常在自定义集合中看到这种行为,因为数组语法是一个众所周知的接口,用于访问集合中的元素,这些元素可以通过键值来识别,通常是它们的位置(如数组和列表中)或者逻辑密钥(如字典和哈希表)。

您可以在MSDN文章索引器(C#编程指南)中找到有关索引器的更多信息。

它是一个索引器,通常用作集合类型类。

看看使用索引器(C#编程指南)