抽象类和继承类中的接口



例如,我有一个具有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);
}
}

这个继承的类现在是否同时具有IEquatableIComparable接口?如果我只通过基类属性检查相等性,我是否应该在继承的类中以不同的方式实现Equals方法?我是否应该IComparable接口添加到基类并使CompareTo方法抽象?例如,如果我想将这些继承的类型存储在仅接受具有这两个接口的类型中的自定义列表中,那么实现这些接口的最佳方法是什么?我可以走一种或另一种方式,在我看来,它仍然有效,但这样做的正确和安全的方法是什么?

抽象类和接口之间有许多细微的区别,但有一个很大的区别:

抽象类位于继承链中。这使它成为主要的、排他性的目的。窗口或窗体不能同时是 DBConnection

接口不在继承链中。

关于无法声明字段的限制被属性无效。如果没有完全删除,否则。

不提供函数实现的限制已在 C# 8.0 中删除

"收集"接口的抽象类是非常常见的景象。

如果我只通过基类属性检查相等性,我是否应该在继承的类中以不同的方式实现 Equals 方法?

无论如何,您应该覆盖它。如果它没有增加任何变化等于,那么实现很简单:

public override bool Equals(Museum other)
{
return base.Equals(other);
}

如果是这样,您可以添加该实现。

1:

最新更新