Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

typeof, GetType, is ใน C# ต่างกันยังไง

typeof(T)

  • Operator: ใช้กับ **Type Name** (Compile-time)
  • Return: System.Type
  • ไม่ต้องมี Instance
Type t = typeof(string); // typeof(DemoClass)

GetType()

  • Method: เรียกบน **Object Instance** (Runtime)
  • Return: System.Type ของ Instance จริง (Polymorphism)
  • Defined ใน System.Object
object obj = "hello";
Type t = obj.GetType(); // typeof(string)

is Keyword

  • Pattern Matching / Type Check
  • Return: bool
  • ใช้ใน Condition
object obj = "hello";
if (obj is string) { ... } // true
if (obj is int) { ... }    // false

ตัวอย่างเปรียบเทียบ

class Demo { }

var demo = new Demo();
Console.WriteLine($"typeof: {typeof(Demo)}");      // ConsoleApp.Demo
Console.WriteLine($"GetType: {demo.GetType()}");   // ConsoleApp.Demo
Console.WriteLine($"is Demo: {demo is Demo}");     // True

สรุป

FeaturetypeofGetType()is
ใช้กับType NameInstanceInstance + Type
ReturnTypeTypebool
TimeCompile-timeRuntimeRuntime
PolymorphismNoYes (Actual Type)Yes