/* 作者: 季健国
* 创建时间: 2012/7/22 15:38:20
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ant.Service.Common
{
///
/// 强制转化辅助类(无异常抛出)
///
public static class ConvertHelper
{
#region 强制转化
///
/// object转化为Bool类型
///
///
///
public static bool ObjToBool(this object obj)
{
bool flag;
if (obj == null)
{
return false;
}
if (obj.Equals(DBNull.Value))
{
return false;
}
return (bool.TryParse(obj.ToString(), out flag) && flag);
}
///
/// object强制转化为DateTime类型(吃掉异常)
///
///
///
public static DateTime? ObjToDateNull(this object obj)
{
if (obj == null)
{
return null;
}
try
{
return new DateTime?(Convert.ToDateTime(obj));
}
catch //(ArgumentNullException ex)
{
return null;
}
}
///
/// int强制转化
///
///
///
public static int ObjToInt(this object obj)
{
if (obj != null)
{
int num;
if (obj.Equals(DBNull.Value))
{
return 0;
}
if (int.TryParse(obj.ToString(), out num))
{
return num;
}
}
return 0;
}
///
/// 强制转化为long
///
///
///
public static long ObjToLong(this object obj)
{
if (obj != null)
{
long num;
if (obj.Equals(DBNull.Value))
{
return 0;
}
if (long.TryParse(obj.ToString(), out num))
{
return num;
}
}
return 0;
}
///
/// 强制转化可空int类型
///
///
///
public static int? ObjToIntNull(this object obj)
{
if (obj == null)
{
return null;
}
if (obj.Equals(DBNull.Value))
{
return null;
}
return new int?(ObjToInt(obj));
}
///
/// 强制转化为string
///
///
///
public static string ObjToStr(this object obj)
{
if (obj == null)
{
return "";
}
if (obj.Equals(DBNull.Value))
{
return "";
}
return Convert.ToString(obj);
}
///
/// Decimal转化
///
///
///
public static decimal ObjToDecimal(this object obj)
{
if (obj == null)
{
return 0M;
}
if (obj.Equals(DBNull.Value))
{
return 0M;
}
try
{
return Convert.ToDecimal(obj);
}
catch
{
return 0M;
}
}
///
/// Decimal可空类型转化
///
///
///
public static decimal? ObjToDecimalNull(this object obj)
{
if (obj == null)
{
return null;
}
if (obj.Equals(DBNull.Value))
{
return null;
}
return new decimal?(ObjToDecimal(obj));
}
#endregion
///
/// 利用反射来判断对象是否包含某个属性
///
/// object
/// 需要判断的属性
/// 是否包含
public static bool ContainProperty(this object instance, string propertyName)
{
if (instance != null && !string.IsNullOrEmpty(propertyName))
{
System.Reflection.PropertyInfo _findedPropertyInfo = instance.GetType().GetProperty(propertyName);
return (_findedPropertyInfo != null);
}
return false;
}
}
}