[C#] How to get/set using index for a Dictionary?
Programming/C# / 2014. 8. 6. 15:50
public class YourClass
{
private readonly IDictionary<string, string> _yourDictionary = new Dictionary<string, string>();
public string this[string key]
{
// returns value if exists
get { return _yourDictionary[key]; }
// updates if exists, adds if doesn't exist
set { _yourDictionary[key] = value; }
}
}
Link : http://stackoverflow.com/questions/11583595/how-to-write-a-getter-and-setter-for-a-dictionary
class SampleCollection<T> { // Declare an array to store the data elements. private T[] arr = new T[100]; // Define the indexer, which will allow client code // to use [] notation on the class instance itself. // (See line 2 of code in Main below.) public T this[int i] { get { // This indexer is very simple, and just returns or sets // the corresponding element from the internal array. return arr[i]; } set { arr[i] = value; } } } // This class shows how client code uses the indexer. class Program { static void Main(string[] args) { // Declare an instance of the SampleCollection type. SampleCollection<string> stringCollection = new SampleCollection<string>(); // Use [] notation on the type. stringCollection[0] = "Hello, World"; System.Console.WriteLine(stringCollection[0]); } } // Output: // Hello, World.
Link : http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx
반응형
'Programming > C#' 카테고리의 다른 글
람다 식 (0) | 2014.08.29 |
---|---|
Get Dictionary key by using the dictionary value (0) | 2014.08.12 |
NTP 서버에서 시간 가져오기(SNTP) (0) | 2014.07.14 |
C# 외부 프로그램 종료하기 (0) | 2014.05.20 |
C# Keywords (0) | 2014.05.13 |