using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Pcb.Common
{
///
/// 对象扩展类
///
/// @2015.8.5
///
public static class ObjectExtension
{
///
/// 判断是NULL或0
///
public static bool IsNullOrZero(this object o)
{
if (o == null) return true;
switch (o.GetType().FullName)
{
case "System.Decimal": return Convert.ToDecimal(o) == 0m;
case "System.Int32": return Convert.ToInt32(o) == 0;
}
return false;
}
/// decimal? To decimal
///
///
///
///
public static decimal ToDecimal(this decimal? source)
{
return source ?? 0;
}
///
/// 非包括空格的空字符串
///
///
///
public static bool IsNotEmptyAndWhiteSpace(this string source)
{
return !string.IsNullOrEmpty(source) && !string.IsNullOrWhiteSpace(source);
}
///
/// 得到一个对象的克隆
///
public static object DeepClone(this object obj)
{
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, obj);
memoryStream.Position = 0;
return formatter.Deserialize(memoryStream);
}
public static SqlParameter[] Copy(this SqlParameter[] source)
{
List target = source.Select(p => new SqlParameter() { ParameterName = p.ParameterName, Value = p.Value }).ToList();
return target.ToArray();
}
///
/// 格式化为指定格式数字(四舍五入),如:73,793.88;
/// digit:小数位数(默认2位,0:没有小数,1:位,2:2位,3:3位);
/// unit:单位(默认为万*=10000, 1:正常,100:百*...);
///
/// 小数位数(默认2位,0:没有小数,1:位,2:2位,3:3位)
/// 单位(默认为万*=10000, 1:正常,100:百*...)
///
public static string FormatNumWithComma(this object value, int digit = 2, int unit = 10000)
{
unit = unit <= 0 ? 1 : unit;
decimal num = 0;
try
{
num = Convert.ToDecimal(value);
}
catch
{
return value.ObjectToString();
}
string format = string.Empty;
if (digit == 0)
format = "{0:#,0}";
else if (digit == 1)
format = "{0:#,0.0}";
else if (digit == 3)
format = "{0:#,0.000}";
else
format = "{0:#,0.00}";
return string.Format(format, (num / decimal.Parse(unit.ToString())));
}
///
/// 格式化为指定格式数字(四舍五入),如:73793.88;
/// digit:小数位数(默认2位,0:没有小数,1:位,2:2位,3:3位);
///
/// 小数位数(默认2位,0:没有小数,1:位,2:2位,3:3位)
///
public static string FormatNum(this object value, int digit = 2)
{
decimal num = 0;
try
{
num = Convert.ToDecimal(value);
}
catch
{
return value.ObjectToString();
}
string format = string.Empty;
if (digit == 0)
format = "{0:0}";
else if (digit == 1)
format = "{0:0.0}";
else if (digit == 3)
format = "{0:0.000}";
else
format = "{0:0.00}";
return string.Format(format, num);
}
public static TOut TransReflection(TIn tIn)
{
TOut tOut = Activator.CreateInstance();
var tInType = tIn.GetType();
foreach (var itemOut in tOut.GetType().GetProperties())
{
var itemIn = tInType.GetProperty(itemOut.Name); ;
if (itemIn != null)
{
itemOut.SetValue(tOut, itemIn.GetValue(tIn));
}
}
return tOut;
}
#region 戴雁冰扩展
///
/// 数据库字段对象转成字符串(null时返回空字符串)
///
public static string _ToStrByDb(this object Src)
{
return Src == DBNull.Value ? "" : Src.ToString();
}
///
/// 对象转成字符串(null时返回空字符串)
///
public static string _ToStr(this object Src)
{
return Src == null ? string.Empty : Src.ToString();
}
///
/// 从当前对象复制到目标对象
///
/// 新对象类型
/// 当前对象
/// 目标对象,null则创建新对象
///
public static TOut _Copy(this object Src, TOut Tgt = null) where TOut : class
{
return Src._Map(Tgt);
}
///
/// 将对象映射到指定类型中
/// create by 戴雁冰
///
/// 新对象类型
/// 当前对象
/// 目标对象,null则创建新对象
public static TOut _Map(this object Src, TOut Tgt = null) where TOut : class
{
if (Tgt == null) { Tgt = Activator.CreateInstance(); }
var tInType = Src.GetType();
foreach (var itemOut in Tgt.GetType().GetProperties())
{
var itemIn = tInType.GetProperty(itemOut.Name);
if (itemIn != null)
{
itemOut.SetValue(Tgt, _Convert(itemIn.GetValue(Src, null), itemOut.PropertyType), null);
}
}
return Tgt;
}
///
/// 将一个对象实例转换为目标类型的对象实例
/// create by 戴雁冰
///
/// 源对象
/// 目标类型
/// 转换后的对象
public static object _Convert(this object Src, Type TgtType)
{
if (TgtType == null) return Src;
if (Src == null) return TgtType.IsValueType ? Activator.CreateInstance(TgtType) : null;
Type srctype = Src.GetType();
//如果待转换对象的类型与目标类型兼容,则无需转换
if (TgtType.IsAssignableFrom(srctype))
{
return Src;
}
Type nulltype = Nullable.GetUnderlyingType(TgtType);
bool isnulltype = nulltype != null;
Type temptype = isnulltype ? nulltype : TgtType;
//如果待转换的对象的基类型为枚举
if (temptype.IsEnum)
{
//如果目标类型为可空枚举,并且待转换对象为null 则直接返回null值
if (isnulltype && string.IsNullOrEmpty(Src.ToString()))
{
return null;
}
else
{
return System.Enum.Parse(temptype, Src.ToString());
}
}
//如果目标类型的基类型实现了IConvertible,则直接转换
if (typeof(IConvertible).IsAssignableFrom(temptype))
{
try
{
return Convert.ChangeType(Src, temptype, null);
}
catch
{
return isnulltype ? null : Activator.CreateInstance(TgtType);
}
}
TypeConverter converter = TypeDescriptor.GetConverter(TgtType);
//是否可以直接转换
if (converter.CanConvertFrom(srctype))
{
return converter.ConvertFrom(Src);
}
//获取构造函数
ConstructorInfo constructor = TgtType.GetConstructor(Type.EmptyTypes);
//是不存在构造函数
if (constructor == null) return Src;
//实例化
object obj = constructor.Invoke(null);
PropertyInfo[] propertys = TgtType.GetProperties();
foreach (PropertyInfo property in propertys)
{
PropertyInfo p = srctype.GetProperty(property.Name);
if (property.CanWrite && p != null && p.CanRead)
{
property.SetValue(obj, _Convert(p.GetValue(Src, null), property.PropertyType), null);
}
}
return obj;
}
///
/// 转换成MVC Json结果
///
/// Json对象
///
public static JsonResult _ToMvcJsonResult(this Object Src)
{
var json = new JsonResult();
json.Data = Src;
json.ContentType = "text/html";
json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return json;
}
///
/// 转换成WebAPI Json结果
///
/// Json对象
///
public static HttpResponseMessage _ToApiJsonResult(this Object Src)
{
var rst = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(JsonConvert.SerializeObject(Src), Encoding.UTF8)
};
return rst;
}
#endregion
}
}