๐ C# GetType() typeof()
@ TODO : ๊ธ ์ ๋ฆฌ
๐
๋ ๋ค Meta-Information ์ ํฌํจํ System.Type ์ ๊ฐ์ ธ์ด
typeof()
() ์์ ํ์ ์ด๋ฆ์(๋ฌธ์์ด์ด ์๋๋ผ ์๋ณ์ Identifier) ๋ฃ๊ณ , ํ์ ์ ๊ฐ์ ธ์ค๋ ํค์๋ (์ปดํ์ผ ํ์ ์์ => ์ ์ ์ธ ํ์ ) ex ) typeof(int) => Int32 typeof(string) => string
GetType()
() ์์ ์ธ์คํด์ค๋ฅผ ๋ฃ๊ณ , ํ์ ์ ๊ฐ์ ธ์ค๋ ํจ์ (๋ฐํ์ ์์ ) ex ) int temp = 0; GetType(temp) => Int32 TempClass temp = new(); GetType(temp) => TempClass
string s = โHiโ; Type t1 = typeof(string); Type t2 = s.GetType();
t1 == t2 ==> true
object obj = โHiโ; Type t1 = typeof(object); // ==> object Type t2 = obj.GetType(); // ==> string
t1 == t2 ==> false
Testing Types ํ์ ์๋ณ์ Testing ์ด๋ผ๊ณ ํํํ๋ ๋ฏ?
if (mycontrol is TextBox) // ==> true != if (mycontrol.GetType() == typeof(TextBox)) // ==> false
์ด๋ ๊ฐ์ง ์๋ค ์๋ํ๋ฉด mycontrol์ด TextBox์๊ฒ derived ํ์๋์ด์ก์ ์ ์๊ธฐ ๋๋ฌธ ์ด ๊ฒฝ์ฐ ์ฒซ ๋ฒ์งธ ์ผ์ด์ค๋ true, ๋ ๋ฒ์งธ ์ผ์ด์ค๋ false ์กฐ๊ฑด์์
TextBox์ ๋ชจ๋ inherit ์์๋ฐ์ ์น๊ตฌ๋ค์ ๊ฐ์ ธ์ ๋น๊ตํ๋ ค๋ฉด is
public class MySpecializedTextBox : TextBox { }
MySpecializedTextBox specialized = new MySpecializedTextBox(); if (specialized is TextBox) ==> true
if (specialized.GetType() == typeof(TextBox)) ==> false
Casting