Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Khác biệt giữa == và .Equals method trong C#


Toán tử so sánh bằng (==) là toán tử so sánh và phương thức Equals() trong C# được dùng để so sánh nội dung của chuỗi.

Phương thức Equals() chỉ so sánh nội dung.

Ví dụ

using System; 

namespace ComparisionExample { 
    class Program { 
        static void Main(string[] args) { 
            string str = "hello"; 
            string str2 = str; 
            Console.WriteLine("Dùng toán tử ==: {0}", str == str2); 
            Console.WriteLine("Dùng equals(): {0}", str.Equals(str2)); 
            Console.ReadKey(); 
        } 
    } 
}

Kết quả

Dùng toán tử ==: True 
Dùng equals(): True

Toán tử == được dùng để so sánh tham chiếu (reference identity).

Hãy xem ví dụ khác.

Ví dụ

using System; 

namespace Demo { 
    class Program { 
        static void Main(string[] args) { 
            object str = "hello"; 
            char[] values = {'h','e','l','l','o'}; 
            object str2 = new string(values); 
            Console.WriteLine("Dùng toán tử ==: {0}", str == str2); 
            Console.WriteLine("Dùng equals(): {0}", str.Equals(str2)); 
            Console.ReadKey(); 
        } 
    } 
}

Kết quả

Dùng toán tử ==: False 
Dùng equals(): True