我很熟悉C#,但這對我來說很奇怪。在一些舊程序中,我看到了這樣的代碼:作爲屬性的'this'關鍵字
public MyType this[string name]
{
......some code that finally return instance of MyType
}
它是如何調用的?這有什麼用處?
我很熟悉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