IEquatable 和继承

IEquatable and inheritance

我如何制作一个 parent 和一个 child 并继承 child 的 IEquatable 函数?这是我的代码

public class Category : IEquatable<Category>
{
   public string _Name { get; set; }
   public string _Id { get; set;}

   private string _HomeCategory { get; set; }  
   public string _prestaId { get; set; }

   public bool _inUse { get; set; }

   public Category(string Name, string Id, string HomeCategory, bool inUse)
    {
        _Name = Name;
        _Id = Id;
        _HomeCategory = HomeCategory;
        _inUse = inUse;
    }

    public virtual bool Equals(Category other)
    {
        if (other == null)
            return false;

        if(this._Id == other._Id)
        {
            return true;
        }
        else { return false; }
    }

    public override int GetHashCode()
    {
        return this._Id.GetHashCode();
    }
}

public class SubCategory : Category :   
{
    public string parentCategory { get; set; }

    public SubCategory(string Name, string Id, string HomeCategory, bool inUse) : base(Name, Id, HomeCategory, inUse)
    {

    }
}

所以我必须 object 并且子类别派生自类别,但是 contain 的方法不适用于子类别,但它适用于类别我做错了什么我如何派生类别的方法以便包含在以子类别作为其类型的列表上是否可行?

看来您需要在 SubCategory 上实施 IEquatable<SubCategory>SubCategory 定义应更改为 public class SubCategory:Category, IEquatable<SubCategory>.

没有这个你将有下一个行为:

var sub = new SubCategory { _Name = "1", parentCategory = "2" };
var x = new List<Category>();
x.Add(sub);
Console.WriteLine(x.Contains(new SubCategory
{
    _Name = sub._Name,
    parentCategory = sub.parentCategory
})); // prints "True"

var y = new List<SubCategory>();
y.Add(sub);
Console.WriteLine(y.Contains(new SubCategory
{
    _Name = sub._Name,
    parentCategory = sub.parentCategory
})); // prints "False"

这是有道理的,因为 SubCategoryIEquatable<Category> 但不是 IEquatable<SubCategory>,并且 IEnumerable.Contains docs 状态:

Elements are compared to the specified value by using the default equality comparer, Default.

它在您的 class 内部使用了 IEquatable<T>.Equals 的实现。

SubCategory 确实继承了bool Equals(Category other),但它会应用于任何 Category实例- 意思是 SubCategoryCategory 如果它们具有相同的 Id,则它们将是 "equal"。

听起来您想要 IEquatable<SubCategory> 的 "automatic" 实现和 bool Equals(SubCategory other) 实现,这是不可能的。您需要显式添加接口声明,但实现应该很简单:

public class SubCategory : Category , IEquatable<SubCategory>  
{
    public string parentCategory { get; set; }

    public SubCategory(string Name, string Id, string HomeCategory, bool inUse) : base(Name, Id, HomeCategory, inUse)
    {

    } 

    public bool Equals(SubCategory other)
    {
        return ((Category).this).Equals((Category)other)
    }
}