对于经常对数据操作的开发者来说,一条记录(MODEL)的数据更改提交,删除等操作,会记录每条记录的详细信息,写入日志表,因此可以采用下面这代码生成一个字符串进行日志记录。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// 日志工具类
    /// </summary>
    public class LogHelper
    {
        /// <summary>
        /// 获取每个对象包含的属性及值的一条字符串,默认以逗号分割
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="item">目标类型对象(实例)</param>
        /// <returns></returns>
        public static string GetInstancePropertyNameValue<T>(T item)
        {
            Type t = typeof(T);
            StringBuilder sb = new StringBuilder();
             System.Reflection.PropertyInfo[] properties = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

            foreach (var i in properties)
            {
                string name = i.Name;
                object value = i.GetValue(item, null);

                if (i.PropertyType.IsValueType || i.PropertyType.Name.StartsWith("String"))
                {
                    sb.Append(string.Format("{0}:{1},", name, value is Nullable ? string.Empty : value));
                }

            }
            return sb.ToString();
        }
    }

 

相关文章:

  • 2022-12-23
  • 2021-11-22
  • 2021-08-21
  • 2022-12-23
  • 2021-09-22
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-02-11
  • 2022-12-23
  • 2021-11-05
  • 2021-07-27
  • 2022-12-23
相关资源
相似解决方案