在C#中,对象的比较和引用是涉及对象相等性和引用的概念。
C#中有两种方式来比较对象的内容:引用相等性比较和值相等性比较。
string str1 = "hello";
string str2 = "hello";
string str3 = string.Copy(str1);
bool referenceEqual = (str1 == str2); // true,引用相等
bool referenceEqual2 = ReferenceEquals(str1, str3); // false,引用不等
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;
Person other = (Person)obj;
return Name == other.Name && Age == other.Age;
}
public override int GetHashCode()
{
return HashCode.Combine(Name, Age);
}
}
Person person1 = new Person { Name = "John", Age = 25 };
Person person2 = new Person { Name = "John", Age = 25 };
Person person3 = new Person { Name = "Alice", Age = 30 };
bool valueEqual = person1.Equals(person2); // true,值相等
bool valueEqual2 = person1.Equals(person3); // false,值不等
Person person1 = new Person { Name = "John", Age = 25 };
Person person2 = person1; // person2引用指向person1引用的对象
person2.Name = "Alice";
Console.WriteLine(person1.Name); // "Alice",person1和person2引用同一个对象
// 引用类型的比较
string str1 = "hello";
string str2 = "hello";
bool referenceEqual = (str1 == str2); // true,引用相等
// 值类型的比较
int num1 = 10;
int num2 = 10;
bool valueEqual = (num1 == num2); // true,值相等