C# 覆写操作符= 实例代码
时间: 2023-07-27 09:14:35 浏览: 149
虽然 C# 中不支持直接重载 `=` 赋值操作符,但是我们可以通过实现 `IEquatable<T>` 接口和 `Clone` 方法来实现类的赋值操作。下面是一个例子:
```csharp
using System;
public class Person : IEquatable<Person>, ICloneable
{
public string Name { get; set; }
public int Age { get; set; }
public bool Equals(Person other)
{
if (other == null) return false;
return (this.Name.Equals(other.Name) && this.Age == other.Age);
}
public override bool Equals(object obj)
{
if (obj == null) return false;
Person personObj = obj as Person;
if (personObj == null) return false;
else return Equals(personObj);
}
public override int GetHashCode()
{
return this.Name.GetHashCode() ^ this.Age.GetHashCode();
}
public object Clone()
{
return new Person { Name = this.Name, Age = this.Age };
}
public static bool operator ==(Person person1, Person person2)
{
if (((object)person1) == null || ((object)person2) == null)
return Object.Equals(person1, person2);
return person1.Equals(person2);
}
public static bool operator !=(Person person1, Person person2)
{
if (((object)person1) == null || ((object)person2) == null)
return !Object.Equals(person1, person2);
return !(person1.Equals(person2));
}
}
```
在这个例子中,我们重载了 `==` 和 `!=` 运算符来比较两个 `Person` 对象是否相等。我们也实现了 `IEquatable<T>` 接口和 `Equals` 方法来比较两个 `Person` 对象是否相等。还实现了 `ICloneable` 接口和 `Clone` 方法来实现对象的克隆。这样,我们就可以在需要时使用 `=` 赋值操作符进行类的赋值操作了。例如:
```csharp
Person person1 = new Person { Name = "Tom", Age = 20 };
Person person2 = new Person { Name = "Tom", Age = 20 };
Person person3 = person1.Clone() as Person;
Console.WriteLine(person1 == person2); // true
Console.WriteLine(person1 == person3); // true
person1.Age = 30;
Console.WriteLine(person1.Age); // 30
Console.WriteLine(person3.Age); // 20
person3 = person1;
Console.WriteLine(person1 == person3); // true
```
阅读全文