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

来源:百度知道 编辑:UC知道 时间:2024/06/30 16:41:36
public class TempClass
{
int a;
int b;
string c;
string d;
bool e;
bool f;

public int A
{
set { a = value; }
get { return a; }
}
public int B
{
set { b = value; }
get { return b; }
}
public string C
{
set { c = value; }
get { return c; }
}
public string D
{
set { d = value; }
get { return d; }
}
public bool E
{
set { e = value; }
get { return e; }
}
public bool F
{
set { f = value; }
get { return f; }
}
}
类很简单 现在我有TempClass的两个实例化TempA和TempB,我如何用反射的方

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;
}

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