Lập trình C# - Sử dụng IEquatable
Sử dụng IEquatable
Được sử dụng so sánh 2 đối tượng có bằng hay không bằng nhau
Bước 1: Kích chuột phải vào Solution chọn Add -> New Project ->Nhập tên (IEquatablePerson)-> Chọn OK
Bước 2: Tạo interface có tên Student chứa các phương thức
using System;
using System.Collections.Generic;
using System.Text;
namespace IEquatablePerson
{
public class Student : IEquatable<Student>
{
public int ID { get; set; }
public string Name { get; set; }
public string Program { get; set; }
public int Year { get; set; }
public float GPA { get; set; }
public bool Equals( Student otherStudent)
{
return (this.ID == otherStudent.ID);
}
}
}
Bước 3: Trong Program code test như sau:
using System;
namespace IEquatablePerson
{
class Program
{
static void Main(string[] args)
{
var studentA = new Student() { ID = 1, Name = "John Doe", Program = "BCS", Year = 2020, GPA = 2.75F };
var studentB = new Student() { ID = 2, Name = "Jane Doe", Program = "BCS", Year = 2020, GPA = 3.4F };
var studentC = new Student() { ID = 1, Name = "John Jane", Program = "BCS", Year = 2019, GPA = 2.71F };
var AtoB = studentA.Equals(studentB);
var AtoC = studentA.Equals(studentC);
Console.WriteLine($"Student A is equal to Student B = {AtoB}");
Console.WriteLine($"Student A is equal to Student C = {AtoC}");
Console.ReadKey();
}
}
}
Bước 4: Nhấn Ctrl+F5 để chạy và xem kết quả
Student A is equal to Student B = False
Student A is equal to Student C = True