2015-11-07 49 views
0

我有一個包含名爲Values的公用字典的類Locale。
我要的是:更改自定義類方括號返回值

Locale l = new Locale(.....); 
// execute stuff that loads the Values dictionary... 
// currently to get the values in it I have to write : 
string value = l.Values["TheKey"]; 
// What I want is to be able to get the same thing using : 
string value = l["TheKey"]; 

我想基本上都採用了自定義類方括號時改變返回值。

+0

您可以創建一個'索引屬性'https://msdn.microsoft.com/en-in/library/aa288464(v=vs.71).aspx –

+1

它被稱爲[索引器](https:// msdn。 microsoft.com/en-us/library/6x16t2tx.aspx)在C#中。 – Han

+0

@ Handoko.Chen是的!對。 –

回答

1

正如評論中所述,您可以爲您的課程Locale實施indexer

public class Locale 
{ 
    Dictionary<string, string> _dict; 
    public Locale() 
    { 
     _dict = new Dictionary<string, string>(); 
     _dict.Add("dot", "net"); 
     _dict.Add("java", "script"); 
    } 
    public string this[string key] //this is the indexer 
    { 
     get 
     { 
      return _dict[key]; 
     } 
     set //remove setter if you do not need 
     { 
      _dict[key] = value; 
     } 
    } 
} 

用法:

var l = new Locale(); 
var value = l["java"]; //"script" 

這裏是MSDN參考。

+0

謝謝!我得到了它的工作。 – Simon56

+0

@ Simon56你可以接受答案,如果它解決了你的問題:) –