ASP.Net 反射简单工厂模式

SqlDal中


public int AddUser<T>(T model) where T : class, new()
        {
          return  connection.Execute(GetSQLStr<T>(model));
        }

        public List<T> GetList<T>() where T : class, new()
        {
            return connection.Query<T>("").AsList();
        }
/// <summary>
        /// 反射
        /// </summary>
        /// <typeparam name="T"><peparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public string GetSQLStr<T>(T model) where T:class,new()
        {
            Type type = model.GetType();

            string tableName = type.Name.Replace("Model","");

            string _fields = "";

            string _values = "";
            //获取属性

            PropertyInfo[] properties = type.GetProperties();

            for(int i=0;i<properties.Length;i++)
            {
                if(properties[i].Name.ToLower().Contains("id"))
                {
                    continue;
                }

                if(i+1==properties.Length)
                {
                    _fields += properties[i].Name;
                    _values += "'" + properties[i].GetValue(model) + "'";
                }
                else
                {
                    _fields += properties[i].Name + ",";
                    _values += "'" + properties[i].GetValue(model) + "',";
                }
            }
            string sql = $"insert into TB_{tableName}({_fields}) values({_values})";

            return sql;
        }


MySqlDal中

 public int AddUser<T>(T model) where T : class, new()
        {
            return connection.Execute("");
        }

        public List<T> GetList<T>() where T : class, new()
        {
           return connection.Query<T>("select *from user").AsList();
        }


 public static IUserDAL CreateInstance(string typeName)
        {
            switch (typeName.ToLower())
            {
                case "sql":
                    return new SqlUserDAL();
                case "mysql":
                    return new MySqlUserDAL();
                default:
                    return null;
            }
        }


Factory中


 public static IUserDAL CreateInstance(string typeName)
        {
            switch (typeName.ToLower())
            {
                case "sql":
                    return new SqlUserDAL();
                case "mysql":
                    return new MySqlUserDAL();
                default:
                    return null;
            }
        }

posted @ 2020-06-16 20:42  我是一只快乐的码农  阅读(98)  评论(0编辑  收藏  举报