を使用するときは、適切な比較を実行しようとしていますList.Contains(T item)
。
問題はBaseItem
、リスト項目として使用していることです。そして、リスト内の 1 つのオブジェクトに、追加する予定のオブジェクトと同じプロパティ値があるかどうかを確認する必要があります。
例えば:
public abstract class BaseItem
{
// some properties
public override bool Equals(object obj)
{
return obj != null && this.GetType() == obj.GetType();
}
}
public class ItemA : BaseItem
{
public int PropertyA { get; set; }
public override bool Equals(object obj)
{
if (base.Equals(obj) == false)
return false;
return (this.PropertyA == (obj as ItemA).PropertyA;
}
}
public class ItemB : BaseItem
{
public int PropertyB { get; set; }
public override bool Equals(object obj)
{
if (base.Equals(obj) == false)
return false;
return this.PropertyB == (obj as ItemB).PropertyB;
}
}
public class Program
{
static void Main(string[] args)
{
List<BaseItem> items = new List<BaseItem>()
{
new ItemB() { PropertyB = 3 },
new ItemA() { PropertyA = 2 },
new ItemB() { PropertyB = 2 }
};
BaseItem newItem = new ItemA() { PropertyA = 2 };
items.Contains(newItem); // should return 'True', because the first element is equals than 'newItem'
}
}
メソッドをオーバーライドするのが正しいのか、Equals
それとも IEquality インターフェイスを実装する必要があるのか わかりません。