C# 物件比較(值型別、引用型別)

衣舞晨風發表於2015-10-09
        #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



小注:

如果傳入的兩個值是dataRow中單元格的值,請先比較型別,型別一致再呼叫該方法

深拷貝部分程式碼:

C# 實體類序列化與反序列化一 (XmlSerializer)

C# 實體類序列化與反序列化二 (DataContractSerializer)

相關文章