#region //两个值是否相等
/// <summary>
/// 比较两个object对象值是否相等,用Equal和RefrenceEqual或者==都不能直接比较
/// 可以用static class扩展object类型
/// </summary>
/// <param name="a">数值a</param>
/// <param name="b">数值b</param>
/// <param name="类型">S,N,D,L,O几个类型</param>
/// <returns></returns>
public static bool 两个值是否相等(object a, object b, string 类型 = "")
{
bool result = false, l1 = false, l2 = false;
if ((l1 = (a == null || a == DBNull.Value)) && (l2 = (b == null || b == DBNull.Value))) return true; //两个都是null
if (l1 != l2) return false; //一个是null一个不是null
//根据传入的类型判断
string sType = 类型.ToUpper();
if (sType == "N") return Convert.ToDouble(a) == Convert.ToDouble(b);
if (sType == "S") return a.ToString() == b.ToString();
if (sType == "D") return Convert.ToDateTime(a) == Convert.ToDateTime(b);
if (sType == "L") return Convert.ToBoolean(a) == Convert.ToBoolean(b);
if (sType != "") return object.Equals(a, b);
//是否数字
if (GsDefineTypes.isNumber(a.GetType()) && GsDefineTypes.isNumber(b.GetType())) return Convert.ToDouble(a) == Convert.ToDouble(b);
return object.Equals(a, b);
}
#endregion
#region //getDefaultValueOfType:取类型的默认值
/// <summary>
/// 取类型的默认值,比default(T)好在便于控制
/// </summary>
/// <param name="type">要取的类型</param>
/// <returns>返回默认值,object类型返回DBNull</returns>
public static object getDefaultValueOfType(Type type)
{ //取类型的默认值
object result = null;
if (isNumber(type)) result = 0;
else if (type == typeof(System.Boolean) || type == typeof(System.Boolean?)) result = false;
else if (type == typeof(System.Byte)) result = 1;
else if (type == typeof(System.SByte)) result = 1;
else if (type == typeof(System.Char)) result = "";
else if (type == typeof(System.String)) result = "";
//其他类型
else if (type == typeof(System.DateTime) || type == typeof(System.DateTime?)) result = DateTime.Today;
else if (type == typeof(System.Guid)) result = Guid.NewGuid();
//全部都不是,只是基类
else if (type == typeof(System.Object)) result = null;
//
return result;
}
#endregion
#region //是数字类型isNumber
public static bool isNumber(Type type)
{
bool result = false;
if (type == typeof(System.Decimal) || type == typeof(System.Decimal?)) result = true;
else if (type == typeof(System.Double) || type == typeof(System.Double?)) result = true;
else if (type == typeof(System.Single) || type == typeof(System.Single?)) result = true;
else if (type == typeof(System.Int16) || type == typeof(System.Int16?)) result = true;
else if (type == typeof(System.UInt16) || type == typeof(System.UInt16?)) result = true;
else if (type == typeof(System.Int32) || type == typeof(System.Int32?)) result = true;
else if (type == typeof(System.UInt32) || type == typeof(System.UInt32?)) result = true;
else if (type == typeof(System.Int64) || type == typeof(System.Int64?)) result = true;
else if (type == typeof(System.UInt64) || type == typeof(System.UInt64?)) result = true;
//
return result;
}
#endregion
直接用==、equal、refrenceEqual判断不大行。
比如一个int和一个double都是0,直接object.equal返回是不相等,因为一个是int一个double。
|