| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- namespace CommonTool
- {
-
- public class ModelToStr
- {
- /// <summary>
- /// 把实体对象的属性与值变成字符串
- /// </summary>
- /// <param name="model">实体对象</param>
- /// <returns></returns>
- public static string ToModelStr<T>(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;
- }
- /// <summary>
- /// 把实体对象的属性与值变成字符串
- /// </summary>
- /// <returns></returns>
- public static T ToStrModel<T>(string modelStr)
- where T : class, new()
- {
- if (modelStr == null)
- return null;
- T model=new T();
- Type type = model.GetType();
- Dictionary<string,object> dict=new Dictionary<string, object>();
- 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;
- }
- /// <summary>
- /// 把实体对象的属性与值转成字符串再转成实体对象
- /// </summary>
- /// <param name="model">实体对象</param>
- /// <returns></returns>
- public static T ModelStrModel<T>(T model)
- where T : class, new()
- {
- if (model == null)
- return null;
- return ToStrModel<T>(ToModelStr(model));
- }
- }
- }
|