Home > Article > Backend Development > C# object comparison (value type, reference type)
<pre class="csharp"><pre class="csharp"> #region 引用对象比较 /// <summary> /// 引用对象比较 /// </summary> /// <param name="objA"></param> /// <param name="objB"></param> /// <returns></returns> public static bool CompareObject(object objA, object objB) { bool flag = false; if (objA == null || objB == null) { flag = false; } else if (objA == DBNull.Value && objB != DBNull.Value) { flag = false; } else if (objA != DBNull.Value && objB == DBNull.Value) { flag = false; } else if (objA == DBNull.Value && objB == DBNull.Value) { //objA objB 对应的列类型已经比较过 类型已判断 值一致 flag = true; } else if (objA.GetType() != objB.GetType()) { flag = false; } else if (objA is int || objA is short || objA is long || objA is float || objA is double || objA is decimal) { //int 01与1 if (objA is int) { if ((int)objA == (int)objB) { flag = true; } } else if (objA is short) { if ((short)objA == (short)objB) { flag = true; } } else if (objA is long) { if ((long)objA == (long)objB) { flag = true; } } else if (objA is float) { if ((float)objA == (float)objB) { flag = true; } } else if (objA is double) { if ((double)objA == (double)objB) { flag = true; } } else if (objA is decimal) { if ((decimal)objA == (decimal)objB) { flag = true; } } } else { string strA = MetadataXmlSerializer<object>.ToXMLString(objA); string strB = MetadataXmlSerializer<object>.ToXMLString(objB); if (strA == strB) { flag = true; } } return flag; } #endregion
## Small note:
If The two values passed in are the values of the cells in dataRow. Please compare the types first, and then call this method if the types are consistent.
Deep copy part of the code:
C# Entity class serialization and deserialization (XmlSerializer)
C# Entity class serialization and deserialization Deserialization 2 (DataContractSerializer)
The above is the content of C# object comparison (value type, reference type). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!