C#,比較兩個實體類對象的值是否一樣:
#region 方法
/// <summary>
/// 比較--兩個類型一樣的實體類對象的值
/// </summary>
/// <param name="oneT"></param>
/// <returns></returns>
private bool CompareType<T>(T oneT, T twoT)
{
#region
bool result = true;//兩個類型作比較時使用,如果有不一樣的就false
Type typeOne = oneT.GetType();
Type typeTwo = twoT.GetType();
//如果兩個T類型不一樣 就不作比較
if (!typeOne.Equals(typeTwo)) { return false; }
PropertyInfo[] pisOne = typeOne.GetProperties(); //獲取所有公共屬性(Public)
PropertyInfo[] pisTwo = typeTwo.GetProperties();
//如果長度爲0返回false
if (pisOne.Length <= 0 || pisTwo.Length <= 0)
{
return false;
}
//如果長度不一樣,返回false
if (!(pisOne.Length.Equals(pisTwo.Length))) { return false; }
//遍歷兩個T類型,遍歷屬性,並作比較
for (int i = 0; i < pisOne.Length; i++)
{
//獲取屬性名
string oneName = pisOne[i].Name;
string twoName = pisTwo[i].Name;
//獲取屬性的值
object oneValue = pisOne[i].GetValue(oneT, null);
object twoValue = pisTwo[i].GetValue(twoT, null);
//比較,只比較值類型
if ((pisOne[i].PropertyType.IsValueType || pisOne[i].PropertyType.Name.StartsWith("String")) && (pisTwo
[i].PropertyType.IsValueType || pisTwo[i].PropertyType.Name.StartsWith("String")))
{
if (oneName.Equals(twoName))
{
if (oneValue == null)
{
if (twoValue != null)
{
result = false;
break; //如果有不一樣的就退出循環
}
}
else if (oneValue != null)
{
if (twoValue != null)
{
if (!oneValue.Equals(twoValue))
{
result = false;
break; //如果有不一樣的就退出循環
}
}
else if (twoValue == null)
{
result = false;
break; //如果有不一樣的就退出循環
}
}
}
else
{
result = false;
break;
}
}
else
{
//如果對象中的屬性是實體類對象,遞歸遍歷比較
bool b = CompareType(oneValue, twoValue);
if (!b) { result = b; break; }
}
}
return result;
#endregion
}
#endregion
//調用
private void btnOrder_Click(object sender, EventArgs e)
{
//實體類比較
UserVo userVoOne = new UserVo();
UserVo userVoTwo = new UserVo();
userVoOne.UserID = 1;
//userVoOne.UserAccount = "a";
userVoTwo.UserID = 1;
bool flag = CompareType(userVoOne, userVoTwo);
if (flag)
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
}
}