2017-08-24 83 views
1

我將ProductBO對象發佈到HttpPost服務,但是當比較它時返回false。比較WebApi中的兩個對象HttpPost請求不起作用

我添加調試器和評估(快速監視)值的在運行時,這兩個類的所有其他成員都是平等的,但是當我比較product.Equals(testProduct)它retuns假的。我將數據作爲..

我傳遞使用郵差數據在原始

{ 
    "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"); 
    } 

回答

5

對於引用類型,該方法Equals比較對象的引用,並將其返回false因爲testProductproduct是指向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; 
    } 
} 
0

由於docs

如果當前實例是引用類型,則等於(Object)方法 測試引用相等,並且調用Equals(Object)方法 相當於調用了ReferenceEquals方法。參考 相等意味着被比較的對象變量指的是同一個對象的 。

在你的情況下,你想比較對象的內容而不是他們的參考。實現此目的的簡單解決方案是將兩個對象序列化爲json並比較字符串

JsonConvert.SerializeObject(product) == JsonConvert.SerializeObject(testProduct)