我试图将2个对象与属性和子属性进行比较。即使对象值匹配,以下代码也始终返回false。在这种情况下,比较的最佳选择是什么?
Student a = new Student();
a.Name = "john";
a.Address ="CA";
//a.StudDetails.Location = "LA";
//a.StudDetails.Study = "MBA";
//a.StudDetails.Friends = new string[] { "X", "Y"};
Student b = new Student();
b.Name = "john";
b.Address = "CA";
//b.StudDetails.Location = "LA";
//b.StudDetails.Study = "MBA";
//b.StudDetails.Friends = new string[] { "X", "Y"};
bool x = Equals(a, b);
if (x)
{
Console.WriteLine("matched");
}
else
{
Console.WriteLine("Not Matched");
}
public class Student
{
public string Name;
public Details StudDetails;
public string Address;
}
public class Details
{
public string Study;
public string Location;
public string[] Friends;
}
答案 0 :(得分:1)
您必须在学生https://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx
上实施等于public class Details
{
public string Study;
public string Location;
public string[] Friends;
}
public class Student
{
public string Name;
public Details StudDetails;
public string Address;
public override bool Equals(Object obj)
{
// Check for null values and compare run-time types.
if (obj == null || GetType() != obj.GetType())
return false;
Student s = (Student)obj;
return (Name == s.Name) && (Address == s.Address);
}
}
Student a = new Student();
a.Name = "john";
a.Address ="CA";
//a.StudDetails.Location = "LA";
//a.StudDetails.Study = "MBA";
//a.StudDetails.Friends = new string[] { "X", "Y"};
Student b = new Student();
b.Name = "john";
b.Address = "CA";
//b.StudDetails.Location = "LA";
//b.StudDetails.Study = "MBA";
//b.StudDetails.Friends = new string[] { "X", "Y"};
bool x = a.Equals(b);
Console.WriteLine( x );
此代码打印" True"。