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

เมธอด Type.Equals() ใน C#

เมธอด Type.Equals() ใน C# ตรวจสอบว่า System Type พื้นฐานของ Type ปัจจุบัน เท่ากับ Type หรือ Object ที่ระบุหรือไม่

ไวยากรณ์

public virtual bool Equals(Type o);
public override bool Equals(object o);

ตัวอย่างที่ 1: เปรียบเทียบ Type ต่างกัน

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        Type val1 = typeof(System.UInt16);
        Type val2 = typeof(System.Int32);
        
        Console.WriteLine("Are both the types equal? " + val1.Equals(val2));
    }
}

ผลลัพธ์

Are both the types equal? False

ตัวอย่างที่ 2: เปรียบเทียบผ่าน GetTypeInfo()

using System;
using System.Reflection;

public class Demo
{
    public static void Main(string[] args)
    {
        Type type = typeof(String);
        Object obj = typeof(String).GetTypeInfo();
        Type type2 = obj as Type;
        
        if (type2 != null)
            Console.WriteLine("Both types are equal? " + type.Equals(type2));
        else
            Console.WriteLine("Cannot cast!");
    }
}

ผลลัพธ์

Both types are equal? True

การใช้งาน: เปรียบเทียบ Type ใน Reflection, Generic Constraints, Serialization เป็นต้น