Reflection
๋ฆฌํ๋ ์ ์ ์ด์ฉํด์ ๋์ ์ธ์คํด์ค๋ฅผ ์์ฑํ๊ธฐ ์ํด์๋ ์๋์ ๊ฐ์ด ์ ์ธํด์ฃผ๋ฉด ๋๋ค.
object a = Activator.CreateInstance(Type);
์ด๋ฒ์๋ Inventory๋ผ๋ ํด๋์ค๋ฅผ ๋ง๋ค์ด์ Inventory ์ธ์คํด์ค๋ฅผ ๋์ ์ผ๋ก ์์ฑํด๋ณด์.
class Inventory
{
private string product;
private int count;
public Inventory()
{
product = "";
count = 0;
}
public Inventory(string product, int count)
{
this.product = product;
this.count = count;
}
public void Print()
{
Console.WriteLine($"{product}: {count}");
}
public string Product
{
get { return product; }
set { product = value; }
}
public int Count
{
get { return count; }
set { count = value; }
}
}
Inventory ํด๋์ค ์์๋ product, count ํ๋, Print๋ผ๋ ๋ฉ์๋, Product, Count ํ๋กํผํฐ๊ฐ ์๋ค.
์ด ๋, ๋์ ์ธ์คํด์ค๋ฅผ ์์ฑํ๊ณ ๊ฐ์ setํด์ฃผ๋ ๋ฐฉ๋ฒ์ ๋ ๊ฐ์ง ๋ชจ๋ ๊ฐ๋ค.
object inventory = Activator.CreateInstance(type, "Grape", 12); // ์์ฑ์์ "Grape"์ 12๋ฅผ ์ธ์๋ก ์ ๋ฌํ์ฌ ์ธ์คํด์ค๋ฅผ ์ด๊ธฐํ
inventory = Activator.CreateInstance(type); // ์ธ์ ์์ด ์์ฑ์๋ฅผ ํธ์ถํ์ฌ ์ธ์คํด์ค๋ฅผ ์์ฑ
productProperty.SetValue(inventory, "Pear", null); // null์ ๋ฐฐ์ด๊ณผ ๊ฐ์ ๊ฒ์ ๋ค๋ฃฐ ๋ index๋ฅผ ๋ฃ๋ ๊ณณ
countProperty.SetValue(inventory, 3, null);
์ด์ ์ธ์คํด์ค ํ์ ์ ๋์ ์ผ๋ก ์์ฑํด๋ณด์.
์ ์ ์ธ์คํด์ค์ ์ฐจ๋ณ์ ๋๊ธฐ ์ํด ์ผ๋ถ๋ก instanceType์ด ๋ฐ๋๋๋ก ํด๋์๋ค.
static void Main(string[] args)
{
for (int i = 0; i < 4; i++) {
string instanceType = (i % 2 == 0) ? "ReflectionPractice.Inventory" : "NothingHere";
Type type = Type.GetType(instanceType);
// NothingHere์ธ ๊ฒฝ์ฐ์๋ type์ null์ด ๋ด๊น
// instanceType์ด ReflectionPractice.Inventory์ธ ๊ฒฝ์ฐ์๋ง ์์
์คํ
if (type == typeof(ReflectionPractice.Inventory)) {
MethodInfo methodInfo = type.GetMethod("Print");
PropertyInfo productProperty = type.GetProperty("Product");
PropertyInfo countProperty = type.GetProperty("Count");
// ๋์ ์ธ์คํด์ค ์์ฑ ํ ์ด๊ธฐํ ๋ฐฉ๋ฒ 1
object inventory = Activator.CreateInstance(type, "Grape", 12);
methodInfo.Invoke(inventory, null);
// ๋์ ์ธ์คํด์ค ์์ฑ ํ ์ด๊ธฐํ ๋ฐฉ๋ฒ 2
inventory = Activator.CreateInstance(type);
productProperty.SetValue(inventory, "Pear", null);
countProperty.SetValue(inventory, 3, null);
Console.WriteLine($"{productProperty.GetValue(inventory, null)}: {countProperty.GetValue(inventory, null)}");
}
else {
Console.WriteLine("^__^");
}
}
}
Grape: 12
Pear: 3
^__^
Grape: 12
Pear: 3
^__^
์ ์ฒด ์ฝ๋๋ Github์ ์ฌ๋ ค๋จ์ต๋๋ค
'๐ฅ๏ธ > C#' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C#] ์ค๋ ๋(Thread) (0) | 2023.10.11 |
---|---|
[C#] ๋ฆฌํ๋ ์ (Reflection): ๋์ ๋ฉ์๋ ์์ฑํ๊ธฐ (3) | 2023.10.11 |
[C#] ๋ฆฌํ๋ ์ (Reflection) (0) | 2023.10.10 |
[์ด๊ฒ์ด C#์ด๋ค] Chapter15: ์ฐ์ต๋ฌธ์ (LINQ) (0) | 2023.10.05 |
[C#] ๋๋ค์๊ณผ Func, Action ๋๋ฆฌ์ (0) | 2023.09.18 |