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

เมธอด SByte.GetTypeCode() ใน C# พร้อมตัวอย่าง


เมธอด SByte.GetTypeCode() ใน C# ใช้สำหรับคืนค่า TypeCode ของประเภทค่า SByte ซึ่งจะคืนค่า TypeCode.SByte เสมอ

ไวยากรณ์ (Syntax)

public TypeCode GetTypeCode ();

ตัวอย่างที่ 1: GetTypeCode กับ SByte และ Object

using System;

public class Demo
{
    public static void Main()
    {
        sbyte s1 = 55;
        object s2 = (sbyte)55;

        Console.WriteLine("Value of S1 = " + s1);
        Console.WriteLine("Value of S2 = " + s2);

        int res = s1.CompareTo(s2);
        if (res > 0)
            Console.WriteLine("s1 > s2");
        else if (res < 0)
            Console.WriteLine("s1 < s2");
        else
            Console.WriteLine("s1 = s2");

        Console.WriteLine("HashCode for s1 = " + s1.GetHashCode());
        Console.WriteLine("GetTypeCode for s1 = " + s1.GetTypeCode());
        Console.WriteLine("HashCode for s2 = " + ((sbyte)s2).GetHashCode());
    }
}

ผลลัพธ์

Value of S1 = 55
Value of S2 = 55
s1 = s2
HashCode for s1 = 55
GetTypeCode for s1 = SByte
HashCode for s2 = 55

ตัวอย่างที่ 2: GetTypeCode กับค่าต่างกัน

using System;

public class Demo
{
    public static void Main()
    {
        sbyte s1 = 10;
        sbyte s2 = 100;

        Console.WriteLine("Value of S1 = " + s1);
        Console.WriteLine("Value of S2 = " + s2);

        int res = s1.CompareTo(s2);
        if (res > 0)
            Console.WriteLine("s1 > s2");
        else if (res < 0)
            Console.WriteLine("s1 < s2");
        else
            Console.WriteLine("s1 = s2");

        Console.WriteLine("HashCode for s1 = " + s1.GetHashCode());
        Console.WriteLine("GetTypeCode for s1 = " + s1.GetTypeCode());
        Console.WriteLine("HashCode for s2 = " + s2.GetHashCode());
        Console.WriteLine("GetTypeCode for s2 = " + s2.GetTypeCode());
    }
}

ผลลัพธ์

Value of S1 = 10
Value of S2 = 100
s1 < s2
HashCode for s1 = 10
GetTypeCode for s1 = SByte
HashCode for s2 = 100
GetTypeCode for s2 = SByte

ข้อสังเกต

  • GetTypeCode() คืนค่า TypeCode.SByte สำหรับทุกค่า SByte — ไม่ขึ้นกับค่าที่เก็บอยู่
  • ประโยชน์หลักคือการตรวจสอบประเภทข้อมูลใน runtime โดยไม่ต้องใช้ Reflection
  • เมื่อ SByte ถูกบอกซ์เป็น object การเรียก GetTypeCode() ผ่าน object จะทำงานได้ (เพราะ SByte override เมธอดนี้)
  • TypeCode ใช้ในการสลับ (switch) ประเภทข้อมูลหรือ serialization