第十天超级基类重写
C#类库开发示例及在项目中该类库的方法
C#重写Equals()
C#重写ToString
C#用户空间的Dispose方法重写
重写 Finalize 方法
using System;
namespace 第十天超级基类重写
{
class Program
{
static void Main(string[] args)
{
var c1 = new Cat { Species = "品种_橘猫", Coatcolor = "毛色_黄色", Weight = 2 };
var c2 = new Cat { Species = "品种_橘猫", Coatcolor = "毛色_黄色", Weight = 2 };
Console.WriteLine($"同一只:{c1.Equals(c2)}");
if (c1 != c2) Console.WriteLine("不是同一只");
else Console.WriteLine("同一只: Ture");
Console.WriteLine(c1);
Console.Read();
}
}
class Cat : Object
{
public string Species { get; set; }
public string Coatcolor { get; set; }
public int Weight { get; set; }
public override string ToString()
{
return $"这只猫的品种是:{this.Species},毛色是:{this.Coatcolor},体重是:{this.Weight}kg。";
}
public override bool Equals(object obj)
{
if (obj == null) return false;
if (this.GetType() != obj.GetType()) return false;
return Equals((Cat)obj);
}
public bool Equals(Cat o)
{
if (o == null) return false;
if (this.GetHashCode() != o.GetHashCode()) return false;
return true ;
}
public override int GetHashCode()
{
return this.Species.GetHashCode() + this.Coatcolor.GetHashCode() + this.Weight.GetHashCode();
}
public static bool operator !=(Cat C1, Cat C2)
{
if (C1 is null) return false;
if (ReferenceEquals(C2, null)) return false;
if (C1.GetHashCode() != C2.GetHashCode()) return true;
return false;
}
public static bool operator ==(Cat C1, Cat C2)
{
if (ReferenceEquals(C1, null)) return false;
if (ReferenceEquals(C2, null)) return false;
if (C1.GetHashCode() == C2.GetHashCode()) return true;
return false;
}
}
}
|