例如,我有一个具有IEquatable
接口的抽象类。基于此类的属性,我想自己实现Equals
方法(因为继承的类将通过这些基本属性检查相等性):
abstract class Site : IEquatable<Site>
{
public string Name { get; set; }
public string Adress { get; set; }
public int Year { get; set; }
public Site() { }
public Site(string name, string adress, int year)
{
Name = name;
Adress = adress;
Year = year;
}
public abstract bool CheckIfNew();
public override bool Equals(object other)
{
if(ReferenceEquals(null, other))
{
return false;
}
if(ReferenceEquals(this, other))
{
return true;
}
return GetType() == other.GetType() && Equals((Site)other);
}
public bool Equals(Site other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return other.Name == Name && other.Adress == Adress;
}
public override int GetHashCode()
{
return Name.GetHashCode() ^ Adress.GetHashCode();
}
}
假设我有两个继承的类。它们都具有IComparable
接口,用于将它们排序在列表中。这是其中之一:
class Museum : Site, IComparable<Museum>
{
public string Type { get; set; }
private int[] WorkDays { get; set; }
public bool HasGuide { get; set; }
public decimal TicketPrice { get; set; }
public Museum(string name, string adress, int year, string type, int[] workDays, bool hasGuide, decimal ticketPrice)
: base(name, adress, year)
{
Type = type;
WorkDays = workDays;
HasGuide = hasGuide;
TicketPrice = ticketPrice;
}
public bool CheckAvailability(int weekDay)
{
return WorkDays[weekDay - 1] == 1;
}
public override bool CheckIfNew()
{
DateTime curent = DateTime.Now;
int difference = curent.Year * 12 + curent.Month - Year * 12;
return difference < 24;
}
public bool Equals(Museum other)
{
return base.Equals(other);
}
public override string ToString()
{
return base.ToString() + string.Format($" {Type, -20} | {(HasGuide ? "Taip" : "Ne"), -5} | {TicketPrice, 6}");
}
public int CompareTo(Museum other)
{
return TicketPrice > other.TicketPrice ? 1 : (TicketPrice < other.TicketPrice ? -1 : 0);
}
}
此继承的类现在同时具有IEquatable
和IComparable
接口吗?如果仅通过基类属性检查相等性,是否应该在继承的类中以不同的方式实现Equals
方法?我应该在基类中添加IComparable
接口,并使CompareTo
方法抽象吗?例如,如果我要将这些继承的类型存储在仅接受具有这两个接口的类型的自定义列表中,那么实现这些接口的最佳方法是什么?我可以选择一种或另一种方法,但我认为它仍然可以工作,但是什么是正确而安全的方法呢?
答案 0 :(得分:1)
抽象类和接口之间有一些细微的差异,但有一个很大的差异:
抽象类在继承链中。这使其成为主要的排他性目的。窗口或窗体也不能是DBConnection
接口不在继承链中。
关于无法正常声明字段的限制已通过“属性”无效。如果没有将其完全删除,那么。
不提供函数实现的限制为removed with C# 8.0
“聚集”接口的抽象类很常见。
如果仅通过基类属性检查相等性,是否应该在继承的类中以不同的方式实现Equals方法?
您仍然应该覆盖它。如果它不增加任何等于等值的值,则实现很简单:
var request = new XMLHttpRequest();
request.open('GET', "{% url 'detail' first."+i+" %}", true)
如果有,您可以添加该实现。
1: