์ํฉ :
๊ณต๋ถํ๊ฑธ ์จ๋จน์ด๋ณด๋ ค๊ณ ์ฝ์ํ๋ฉด๊ธฐ๋ฐ ํ ์คํธ๊ฒ์์ ๋ง๋ค๊ณ ์์
์ผ๋จ
class MyRoom_ {
public string Name { set; } = "๋์ ๋ฐฉ"; }
class Toilet_ {
public string Name { set; } = "ํ์ฅ์ค"; }
์ด๋ ๊ฒ ๋ ๊ฐ์ ํด๋์ค๊ฐ ์๋ค๊ณ ์น๊ณ
ํธ์์ ๊ฐ์ฒด MyRoom์ด๋ ๊ฐ์ฒด Toilet์ ๋ง๋ค์๋ค๊ณ ์ณ
======
ํ๋ ์ด์ด ์์น : ๋์ ๋ฐฉ
======
์๋ฐ ์ํฉ์์ ReadLine() = "Toilet"์ ์ ๋ ฅํ์ ๋
======
ํ๋ ์ด์ด ์์น : ํ์ฅ์ค
======
์๋ ๊ฒ ๋์ผ๋ฉด ์ข๊ฒ ์. ๊ทธ๋ ๋ค๋ฉด
======
string roomName = ReadLine(); // Toilet์ ์ ๋ ฅํด์ roomName = "Toilet"์ด ๋จ
console.writeline("ํ๋ ์ด์ด ์์น : " + x(string roomName).Name) // ๊ฒฐ๊ณผ : Toilet.Name์ด ์ถ๋ ฅ๋จ
======
์ด๋ฐ ๋๋์ ๋ท๋ท ๊ธฐ๋ณธ ํจ์ x๊ฐ ์ ์ง ์์๊ฑฐ ๊ฐ์๋ฐ ์ฐพ์๋ณด์! ๋ผ๋ ์๊ฐ์ ํจ
๊ทธ๋์ ๊ตฌ๊ธ์ convert string to static class name, convert string to object name ๋ฑ๋ฑ์ ๊ฒ์ํด๋ดค๋๋ฐ
๋๋ ๋๊ฐ์ ์ง๋ฌธ์ stackoverflow๊ฐ์ ๋ฐ๋ค๊ฐ ํ ์ฌ๋๋ค์ด ์ด๋ฏธ ๋ง๋๋ผ๊ตฌ
๊ทธ๋์ ๋ต๋ณ์ ์ฐธ๊ณ ํด์ ์ฝ๋๋ฅผ ๋ง๋ค์๋๋ฐ
Type t = Type.GetType("Toilet");
ConstructorInfo c = t.GetConstructor(Type.EmptyTypes);
var v1 = c.Invoke(new object[] { });
PropertyInfo p = t.GetProperty("Name");
var v2 = p.GetValue(v1);
๋์ถฉ ์ด๋ ๊ฒ ํ๋ฉด ๋๋ค๋ ๊ฒฐ๋ก ์ด ๋์ด. ๊ทธ๋์...
======
Type t = Type.GetType(ReadLine()); // enum ์ฐ๋ ๊ฐ ํด์ ์์ธ ์ฒ๋ฆฌํ๋ค๊ณ ์น๊ณ
ConstructorInfo c = t.GetConstructor(Type.EmptyTypes);
var v1 = c.Invoke(new object[] { });
PropertyInfo p = t.GetProperty("Name");
var v2 = p.GetValue(v1);
Console.WriteLine(("ํ๋ ์ด์ด ์์น : " + v2); // ํ๋ ์ด์ด ์์น : ํ์ฅ์ค
======
์ผ๋จ ์?๋์ ํ๋๋ฐ...
์ด๊ฒ ์ต์ ์?
์ต์ ์ด๋ผ๊ณ ์น๋ฉด..
๋ง์ฝ MyRoom์ด๋ Toilet ํด๋์ค๊ฐ static์ด๋ฉด ์ด๊ฑฐ ์ด์ผ ์ฒ๋ฆฌํจ?
์ง๊ธํ๋๊ฒ C# ๋ฆฌํ๋ ์ ์ ์ด์ฉํ๊ฑฐ์. ๋ฐํ์์์ ์ ๋ ฅํ string์ ๊ฐ์ง๊ณ ํ๋๋ฒ์ ๋๊ฐ ํ๋ ๋ฐฉ๋ฒ๋๋ก๋ ์๊ณ Assembly.CreateInstance๋ฅผ ์ฐ๋ ๋ฒ๋ ์์. ๋๋ค ๋ฆฌํ๋ ์ ์
์ ์ ํด๋์ค๋ค์ ๊ฐ๊ณ ํ๋ฉด ๊ฐ์ฒดํ๊ฐ ์๋ผ์ ๋ชป์ฐ๋ ๊ธฐ๋ฅ์ธ๊ฑฐ ๊ฐ์๋ฐ... ๋์์ด ์์๊น์?
์ผ๋จ ๊ฐ์ฌํฉ๋๋ค ํ๋
๋ฆฌํ๋ ์ ์ ๊ณต๋ถํด๋ด. ์ง๊ธ ๋์ ์์ ๋ ์ผ๋ฐ class์ธ๊ฒฝ์ฐ ์ผ๋จ ๊ฐ์ฒด๋ฅผ ์์ฑํ ๋ค์์ ํ๋๊ฑฐ๊ณ , static ํด๋์ค๋ ์ ์ ํจ์๋ง ๋ฆฌํ๋ ์ ์ผ๋ก ํธ์ถํด์ฃผ๋ฉด ๋๋๊ฑฐ์. ํ๋ก๊ทธ๋๋ฐ ๊ธฐ์ด๋ฅผ ์๋ค๋ฉด, static ํด๋์ค๋ ๊ทธ๋ฐ๊ฒฝ์ฐ ์์ฑ์ ํธ์ถ๋ ํ์๊ฐ ์๋ค๋๊ฑธ ์๊ณ ์๊ฒ ์ง? ๋๊ฐ ์ง๊ธ ํ์ํ๊ฑด ๋ฆฌํ๋ ์ ์ ๊ณต๋ถํ๋ ๊ฒ์. ์๋๋ฉด GPTํํ ๋ฌผ์ด๋ด.
// Get the Type object for the static class Type type = Type.GetType("MyNamespace.MyStaticClass"); // Get the MethodInfo object for the static method MethodInfo methodInfo = type.GetMethod("MyStaticMethod"); // Call the static method using null as the first argument since it doesn't have an instance methodInfo.Invoke(null, null); GPT๊ฐ ๋ฐ๋ก์๋ ค์ฃผ๋ค
ํ ๊ฐ์ฌํฉ๋๋ค