之間的比較,假設我有這些對象字典兩個對象
var address = new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243");
var person = new Person("Jane", "Smith", address);
我想用字典來檢查這些對象的平等,所以它的smiliar這樣
var dictionary = new Dictionary<object>{ [address] = address, [person] = person};
Assert.IsTrue(dictionary.ContainsKey(new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243")));
Assert.IsTrue(dictionary.ContainsKey(new Person("Jane", "Smith", address)));
然而,它總是返回作爲假。我在這裏錯過了什麼?
編輯
添加自定義詞典
public class Dictionary<T> : Dictionary<T, T> where T : class, new()
{
}
添加類
public abstract class BaseModel
{
public string Id { get; set; }
public BaseModel()
{
}
}
public class Address : BaseModel
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public Address() { }
public override bool Equals(object value)
{
if (value == null)
return false;
Address mod = value as Address;
return (mod != null)
&& (Street == mod.Street)
&& (City == mod.City)
&& (PostalCode == mod.PostalCode)
&& (State == mod.State);
}
public override int GetHashCode(){
return base.GetHashCode();
}
public Address(string street, string city, string state, string postalCode) {
this.Street = street;
this.City = city;
this.State = state;
this.PostalCode = postalCode;
}
}
public class Person : BaseModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public Person() { }
public Person(string firstName, string lastName, Address address)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Address = address;
}
public override bool Equals(object value)
{
if (value == null)
return false;
Person mod = value as Person;
return (mod != null)
&& (FirstName == mod.FirstName)
&& (LastName == mod.LastName)
&& (Address.Equals(mod.Address));
}
public override int GetHashCode(){
return base.GetHashCode();
}
}
@DavidL能正常工作在C#6,我也更新了我的問題,有一個自定義詞典 – vantian