[英]Comparing two object in WebApi HttpPost request doesn't work
我將ProductBO對象發布到HttpPost服務,但比較時返回false。
我添加調試器並在運行時評估(QuickWatch)值,兩個類的所有其他成員都相等,但是當我比較product.Equals(testProduct)
它會返回false。 我正在傳遞數據..
我正在原始使用Postman傳遞數據
{
"Id" :1,
"Name" : "Tomato Soup",
"Category" :"Groceries",
"Price" : 1
}
文本類型為application/json
。 我在做什么錯, 以及傳遞這樣的對象是否是更好的方法 。
public IHttpActionResult GetTestProduct(ProductBO testProduct) {
ProductBO product = new ProductBO { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 };
if (product.Equals(testProduct)) //also tried for product == testProduct both return false
{
return Ok(product);
}
if (product.Id == testProduct.Id)
{
}
if (product.Name.Equals(testProduct.Name))
{
}
return Ok("working");
}
對於引用類型, Equals
方法比較對象引用,並返回false
因為testProduct
和product
指向內存中的2個不同地址。 您可以在視圖模型上實現IEquatable<T>
接口,以指示如何執行比較:
public class ProductBO : IEquatable<ProductBO>
{
public int Id { get; set; }
public string Name { get; set; }
public bool Equals(ProductBO other)
{
return this.Id == other.Id && this.Name == other.Name;
}
}
正如文檔所說
如果當前實例是引用類型,則Equals(Object)方法將測試引用是否相等,並且對Equals(Object)方法的調用等效於對ReferenceEquals方法的調用。 引用相等意味着比較的對象變量引用同一對象。
在您的情況下,您想比較對象的內容而不是引用。 實現此目的的簡單解決方案是將兩個對象序列化為json並比較字符串
JsonConvert.SerializeObject(product) == JsonConvert.SerializeObject(testProduct)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.