using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
namespace RM.Web
{
/// <summary>
/// 用于dbnull的数据转换。因为用convert.to无法转换dbnull类型
/// </summary>
public static class ExtendObject
{
public static bool IsTargetType<T>(this object source) where T : IConvertible
{
Type targetType = typeof(T);
var tryParse = targetType.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
new Type[] { typeof(T), targetType.MakeByRefType() },
new ParameterModifier[] { new ParameterModifier(2) });
if (tryParse == null)
return false;
var parameters = new object[] { source, Activator.CreateInstance(targetType) };
if (source is DBNull)
{
return false;
}
return (bool)tryParse.Invoke(null, parameters);
}
public static T ToTargetType<T>(this object source) where T : IConvertible
{
Type targetType = typeof(T);
var parse = targetType.GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
new Type[] { typeof(object) },
new ParameterModifier[] { new ParameterModifier(1) });
if (parse == null)
return default(T);
return (T)parse.Invoke(null, new object[] { source });
}
public static T ToTargetTypeConvert<T>(this object source) where T : IConvertible
{
Type targetType = typeof(T);
return (T)Convert.ChangeType(source, targetType);
}
public static T AsTargetType<T>(this object source, T defaultValue) where T : IConvertible
{
//return source.IsTargetType<T>() ? source.ToTargetTypeConvert<T>() : defaultValue;
return source is DBNull ? defaultValue : source.ToTargetTypeConvert<T>();
}
}
}