,
. , , :
class MyClass {
public string GetValue(string name) {
switch(key)
{
case "Name":
return "John";
case "Age":
return 30;
}
}
}
, , , , :
var instance = new MyClass();
var value = instance.GetValue("Name");
Console.WriteLine(value);
, "indexer".
class MyClass {
public string this[string name] {
switch(key)
{
case "Name":
return "John";
case "Age":
return 30;
}
}
}
:
var instance = new MyClass();
var value = instance["Name"];
Console.WriteLine(value);
When should I use an index instead of a method?
Whenever you want. Whenever you feel it makes sense. It is commonly used when an object stores dynamic values, such as Dictionary <,>, or when you want it to behave like an array, such as List <>.
source
share