เมธอด Type.Equals() ใน C# กำหนดว่าประเภทระบบพื้นฐานของ Type ปัจจุบันเหมือนกับประเภทระบบพื้นฐานของ Object หรือ Type ที่ระบุ
ไวยากรณ์
public virtual bool Equals (Type o); public override bool Equals (object o);
ด้านบน พารามิเตอร์คืออ็อบเจ็กต์ที่มีการเปรียบเทียบประเภทของระบบพื้นฐานกับประเภทระบบพื้นฐานของประเภทปัจจุบัน
ให้เราดูตัวอย่างการใช้วิธีการ Type.Equals() -
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
ให้เราดูตัวอย่างอื่นเพื่อใช้วิธีการ Type.Equals() -
ตัวอย่าง
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