本文介绍了。载有()自定义类对象名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用。载有()
功能自定义对象的名单上。
I'm trying to use the .Contains()
function on a list of custom objects
这清单如下:
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;
}
}
所以,我试图找到列表中的类似cartproduct
So i try to find a similar cartproduct within the list:
if (CartProducts.Contains(p))
但它忽略类似cartproducts,似乎我不知道它会检查 - 的ID?还是这一切?
But it ignores similar cartproducts and i don't seem to know what it checks on - the ID? or it all?
在此先感谢! :)
推荐答案
您需要执行 IEquatable
或覆盖等于()
和的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;
}
}
这篇关于。载有()自定义类对象名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!