。包含自定义类对象列表的()
我正在尝试.Contains()
在自定义对象列表上使用该功能
这是清单:
List<CartProduct> CartProducts = new List<CartProduct>();
和CartProduct
:
public class CartProduct{
public Int32 ID;
public String Name;
public Int32 Number;
public Decimal CurrentPrice;
/// <summary>
///
/// </summary>
/// <param name="ID">The ID of the product</param>
/// <param name="Name">The name of the product</param>
/// <param name="Number">The total number of that product</param>
/// <param name="CurrentPrice">The currentprice for the product (1 piece)</param>
public CartProduct(Int32 ID, String Name, Int32 Number, Decimal CurrentPrice)
{
this.ID = ID;
this.Name = Name;
this.Number = Number;
this.CurrentPrice = CurrentPrice;
}
public String ToString()
{
return Name;
}
}
所以我尝试在列表中找到类似的购物车产品:
if (CartProducts.Contains(p))
但是它忽略了类似的购物车产品,而且我似乎也不知道要检查什么-ID?还是全部?
提前致谢!:)
回答:
您需要实现IEquatable
或重载Equals()
和GetHashCode()
例如:
public class CartProduct : IEquatable<CartProduct>{
public Int32 ID;
public String Name;
public Int32 Number;
public Decimal CurrentPrice;
public CartProduct(Int32 ID, String Name, Int32 Number, Decimal CurrentPrice)
{
this.ID = ID;
this.Name = Name;
this.Number = Number;
this.CurrentPrice = CurrentPrice;
}
public String ToString()
{
return Name;
}
public bool Equals( CartProduct other )
{
// Would still want to check for null etc. first.
return this.ID == other.ID &&
this.Name == other.Name &&
this.Number == other.Number &&
this.CurrentPrice == other.CurrentPrice;
}
}
以上是 。包含自定义类对象列表的() 的全部内容, 来源链接: utcz.com/qa/399130.html