์ธ๋ฑ์(Indexer)
์ธ๋ฑ์๋ ์ธ๋ฑ์ค([])๋ฅผ ์ด์ฉํด์ ๊ฐ์ฒด ๋ด์ ๋ฐ์ดํฐ์ ์ ๊ทผํ ์ ์๊ฒ ํด์ฃผ๋ ํ๋กํผํฐ์ด๋ค. ๋ง์น ๊ฐ์ฒด๋ฅผ ๋ฐฐ์ด์ฒ๋ผ ์ฌ์ฉํ ์ ์๋ค.
1. ๊ตฌํ
- ํน๋ณํ ๋ฌธ๋ฒ์ธ this []๋ฅผ ์จ์ ํด๋์ค ํ๋กํผํฐ์ฒ๋ผ get๊ณผ set์ ์ ์ํ๋ค.
- ์ ๋ ฅ ํ๋ผ๋ฏธํฐ์ธ ์ธ๋ฑ์ค๋ ์ฌ๋ฌ ๋ฐ์ดํฐ ํ์ ์ผ๋ก ์ ์ํ ์ ์๋ค. ์ฃผ๋ก int๋ string ํ์ ์ ์ฌ์ฉํ๋ค.
class ํด๋์ค์ด๋ฆ
{
ํ์ ์ ๋ฐํํ์
this[์
๋ ฅํ์
์
๋ ฅ์ด๋ฆ]
{
get
{
// ๋ด๋ถ ๋ฐ์ดํฐ ๋ฐํ
}
set
{
// ๋ด๋ถ ๋ฐ์ดํฐ ์ ์ฅ
}
}
}
2. ํ์ฉ
1) intํ ์ธ๋ฑ์ค๋ก ๋ฐฐ์ด ์ ๊ทผ
class MyClass
{
private const int MAX = 10;
private string name;
private int[] data = new int[MAX];
// ์ธ๋ฑ์ ์ ์
public int this[int index]
{
get
{
if (index < 0 || index >= MAX)
{
throw new IndexOutOfRangeException();
}
else
{
return data[index];
}
}
set
{
if (!(index < 0 || index >= MAX))
{
data[index] = value;
}
}
}
}
class Program
{
static void Main(string[] args)
{
MyClass cls = new MyClass();
// ์ธ๋ฑ์ set ์ฌ์ฉ
cls[1] = 1024;
// ์ธ๋ฑ์ get ์ฌ์ฉ
int i = cls[1];
}
}
2) intํ ์ธ๋ฑ์ค๋ก ๋ณ์ ์ ๊ทผ
public class Person
{
public string Name { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
public string Email { get; set; }
public Object this [int index]
{
get
{
if (index == 0)
return Name;
else if (index == 1)
return Gender;
else if (index == 2)
return Age;
else if (index == 3)
return Email;
else
return null;
}
set
{
if (index == 0)
Name = value.ToString();
else if (index == 1)
Gender = value.ToString();
else if (index == 2)
Age = Convert.ToInt32(value);
else if (index == 3)
Email = value.ToString();
}
}
public override string ToString()
{
return "Name: " + Name + " / Gender: " + Gender + " / Age: " + Age + " / Email: " + Email;
}
}
class Program
{
static void Main(string[] args)
{
Person person = new Person() {
Name="Tom",
Gender="Male",
Age= 20,
Email="Tom@Test.com"
};
Console.WriteLine("Name: " + person[0]);
Console.WriteLine("Gender: " + person[1]);
Console.WriteLine("Age: " + person[2]);
Console.WriteLine("Email: " + person[3]);
}
}
3) stringํ ์ธ๋ฑ์ค๋ก ๋ณ์ ์ ๊ทผ
public class Person
{
public string Name { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
public string Email { get; set; }
public Object this [int index]
{
get
{
if (indexName.ToUpper() == "NAME")
return Name;
else if (indexName.ToUpper() == "GENDER")
return Gender;
else if (indexName.ToUpper() == "AGE")
return Age;
else if (indexName.ToUpper() == "EMAIL")
return Email;
else
return null;
}
set
{
if (indexName.ToUpper() == "NAME")
Name = value.ToString();
else if (indexName.ToUpper() == "GENDER")
Gender = value.ToString();
else if (indexName.ToUpper() == "AGE")
Age = Convert.ToInt32(value);
else if (indexName.ToUpper() == "EMAIL")
Email = value.ToString();
}
}
public override string ToString()
{
return "Name: " + Name + " / Gender: " + Gender + " / Age: " + Age + " / Email: " + Email;
}
}
์ฐธ๊ณ
https://developer-talk.tistory.com/323