ํฌ์ŠคํŠธ

๐ŸŒ’ 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

์ด ๊ธฐ์‚ฌ๋Š” ์ €์ž‘๊ถŒ์ž์˜ CC BY 4.0 ๋ผ์ด์„ผ์Šค๋ฅผ ๋”ฐ๋ฆ…๋‹ˆ๋‹ค.