บทนำ
เมธอด Uri.Equals() ใน C# ใช้เปรียบเทียบอินสแตนซ์ Uri สองอินสแตนซ์ ว่าเท่ากันหรือไม่ โดยพิจารณาจากส่วนประกอบต่างๆ ของ URI รวมถึง scheme, host, port, path, query และ fragment
ไวยากรณ์ (Syntax)
public override bool Equals (object comparand);
โดยที่ comparand คืออินสแตนซ์ Uri หรือตัวระบุ URI ที่ต้องการเปรียบเทียบกับอินสแตนซ์ปัจจุบัน
ตัวอย่างที่ 1: เปรียบเทียบ URI ที่ต่างกันใน scheme
using System;
public class Demo
{
public static void Main()
{
Uri newURI1 = new Uri("https://www.tutorialspoint.com/index.htm");
Console.WriteLine("URI = " + newURI1);
Uri newURI2 = new Uri("https://www.tutorialspoint.com/index.htm");
Console.WriteLine("URI = " + newURI2);
if (newURI1.Equals(newURI2))
Console.WriteLine("Both the URIs are equal!");
else
Console.WriteLine("Both the URIs aren't equal!");
}
}
ผลลัพธ์
URI = https://www.tutorialspoint.com/index.htm URI = https://www.tutorialspoint.com/index.htm Both the URIs are equal!
ตัวอย่างที่ 2: เปรียบเทียบ URI ที่ต่างกันใน path
using System;
public class Demo
{
public static void Main()
{
Uri newURI1 = new Uri("https://www.tutorialspoint.com/index.htm");
Console.WriteLine("URI = " + newURI1);
Uri newURI2 = new Uri("https://www.tutorialspoint.com/");
Console.WriteLine("URI = " + newURI2);
if (newURI1.Equals(newURI2))
Console.WriteLine("Both the URIs are equal!");
else
Console.WriteLine("Both the URIs aren't equal!");
}
}
ผลลัพธ์
URI = https://www.tutorialspoint.com/index.htm URI = https://www.tutorialspoint.com/ Both the URIs aren't equal!
สรุป
เมธอด Uri.Equals() ทำการเปรียบเทียบแบบปกติ (canonical comparison) โดยจะทำให้ URI อยู่ในรูปแบบมาตรฐานก่อนเปรียบเทียบ ซึ่งรวมถึงการทำให้ตัวอักษรเป็นตัวพิมพ์เล็กสำหรับ scheme และ host การถอดรหัส percent-encoding และการจัดการ default port