using System;
using System.Collections.Generic;
using System.Reflection;
namespace CommonTool
{
public class ModelToStr
{
///
/// 把实体对象的属性与值变成字符串
///
/// 实体对象
///
public static string ToModelStr(T model)
where T : class, new()
{
if (model == null) return "";
string sb = "";
Type type = model.GetType();
PropertyInfo[] propertys = type.GetProperties();
foreach (PropertyInfo prop in propertys)
{
PropertyInfo property = type.GetProperty(prop.Name);
object val = property.GetValue(model, null);
string value = val?.ToString().Trim() ?? "";
sb += prop.Name + '-' + value + '|';
}
if (sb.Length <= 0) return sb;
sb = sb.Substring(0, sb.Length - 1);
return sb;
}
///
/// 把实体对象的属性与值变成字符串
///
///
public static T ToStrModel(string modelStr)
where T : class, new()
{
if (modelStr == null)
return null;
T model=new T();
Type type = model.GetType();
Dictionary dict=new Dictionary();
PropertyInfo[] propertys = type.GetProperties();
string[] objs = modelStr.Split('|');
foreach (string obj in objs)
{
string[] str = obj.Split('-');
dict[str[0]] = str[1];
}
foreach (PropertyInfo prop in propertys)
{
string propType = prop.PropertyType.ToString().ToLower();
if (dict[prop.Name].ToString() == "")
dict[prop.Name] = null;
PropertyInfo property = type.GetProperty(prop.Name);
object value = null;
if (propType.Contains("decimal"))
{
if (dict[prop.Name] != null)
value = Convert.ToDecimal(dict[prop.Name]);
}
else if (propType.Contains("decimal"))
{
if (dict[prop.Name] != null)
value = Convert.ToDecimal(dict[prop.Name]);
}
else if (propType.Contains("int32"))
{
if (dict[prop.Name] != null)
value = Convert.ToInt32(dict[prop.Name]);
}
else if (propType.Contains("int64"))
{
if (dict[prop.Name] != null)
value = Convert.ToInt32(dict[prop.Name]);
}
else if (propType.Contains("datetime"))
{
if (dict[prop.Name] != null)
value = Convert.ToDateTime(dict[prop.Name]);
}
else
{
value = dict[prop.Name];
}
property.SetValue(model,value,null);
}
return model;
}
///
/// 把实体对象的属性与值转成字符串再转成实体对象
///
/// 实体对象
///
public static T ModelStrModel(T model)
where T : class, new()
{
if (model == null)
return null;
return ToStrModel(ToModelStr(model));
}
}
}