c#如何用反射判断同一个类的两个实例的值是否完全一样

2025年03月21日 23:15
有2个网友回答
网友(1):

你可以用this.getClass().getDeclaredFields()然后比较所有基本类型字段。不过最好的方法是重写TempClass的Equals

网友(2):

public static bool ObjectEquel(TempClass obj1, TempClass obj2)
{
Type type1 = obj1.GetType();
Type type2 = obj2.GetType();

System.Reflection.PropertyInfo[] properties1 = type1.GetProperties();
System.Reflection.PropertyInfo[] properties2 = type2.GetProperties();

bool IsMatch = true;
for (int i = 0; i < properties1.Length; i++)
{
string s = properties1[i].DeclaringType.Name;
if (properties1[i].GetValue(obj1, null).ToString() != properties2[i].GetValue(obj2, null).ToString())
{
IsMatch = false;
break;
}
}

return IsMatch;
}