zoukankan      html  css  js  c++  java
  • 泛型反射常见应用,通过类型创建实例,通过反射实现增删改查

    public class Test
        {
    
    
            public void MyObj<T>() where T : class
            {
                //T t = new T();
                T t =System.Activator.CreateInstance<T>();
                //获取类型跟字段然后拿到对应名字方法跟字段就可以了
            }
        }
    

      

    微信官方创建实体的方法,通过泛型类型创建实例
    System.Activator.CreateInstance<T>();





    新增:
    public static void Add<T>(T model)
            {
                Type t = typeof(T);
                string TableName = GetTableName(t);
                PropertyInfo[] pps = t.GetProperties();
                StringBuilder sb = new StringBuilder("insert into"+ TableName + "(");
                StringBuilder sbColumns = new StringBuilder();
                StringBuilder sbValues = new StringBuilder();
                foreach (PropertyInfo item in pps)
                {
                    if (!IsNotMapper(item)&& !IsKey(item))
                    {
                        sbColumns.Append(item.Name+",");
                        if (IsNoStr(item.PropertyType))
                        {
                            
                            if (item.GetValue(model)==null|| string.IsNullOrEmpty(item.GetValue(model).ToString()))
                            {
                                sbValues.Append("null,");
                            }
                            else
                            {
                                
                                if (IsBoolean(item.PropertyType))
                                {
                                    bool bvalue = (bool)item.GetValue(model);
                                    sbValues.Append((bvalue?1:0) + ",");
                                }
                                else
                                {
                                    sbValues.Append(item.GetValue(model) + ",");
                                }
                                
                            }
                        }
                        else
                        {
                            sbValues.Append("'"+item.GetValue(model) + "',");
                        }
                        
                    }
                }
                string sql = string.Format("insert into " + TableName + "({0}) values({1})",sbColumns.ToString().TrimEnd(','), sbValues.ToString().TrimEnd(','));
                connection.Execute(sql);
            }
    

      




    修改:
    public static void Update<T>(T model)
            {
                Type t = typeof(T);
                string TableName = GetTableName(t);
                PropertyInfo[] pps = t.GetProperties();
                StringBuilder sb = new StringBuilder();
                string where = "";
                foreach (PropertyInfo item in pps)
                {
                    if (!IsNotMapper(item))
                    {
                        string column = item.Name;
                        string value = item.GetValue(model).ToString();
                        if (!IsKey(item))
                        {
                            if (IsNoStr(item.PropertyType))
                            {
                                if (IsBoolean(item.PropertyType))
                                {
                                    bool bvalue = (bool)item.GetValue(model);
                                    value = bvalue ? "1" : "0";
                                }
                                sb.Append(column + "=" + value + ",");
                            }
                            else
                            {
                                sb.Append(column + "='" + value + "',");
                            }
                        }
                        else
                        {
                            where = column + "=" + value;
                        }
                    }
                }
    
                string sql = string.Format("update {0} set {1} where {2} ",TableName,sb.ToString().TrimEnd(','),where);
            }
    

      

    删除:

    public static void Delete<Key, T>(Key id)
            {
                Type tp = typeof(T);
                PropertyInfo[] pps = tp.GetProperties();
                string KeyName = "";
                Key Value = id;
                foreach (PropertyInfo item in pps)
                {
                    if (!IsNotMapper(item)&& IsKey(item))
                    {
                        KeyName = item.Name;
                    }
                }
                if (IsNoStr(typeof(Key)))
                {
                    string sql = "delete " + GetTableName(tp) + " where " + KeyName + "=" + Value;
                }
                else
                {
                    string sql = "delete " + GetTableName(tp) + " where " + KeyName + "='" + Value + "'";
                }
            }
    

      

    判断字段或类是否包含特性:

    /// <summary>
            /// 是否包含该特性
            /// </summary>
            /// <param name="item"></param>
            /// <param name="tp"></param>
            /// <returns></returns>
            private static bool IsAttribute(PropertyInfo item, Type tp)
            {
                var attr = item.GetCustomAttributes(tp, true);
                if (attr.Length <= 0)
                    return false;
                return true;
            }
    

      

    抓取指定特性值(如表名,子段说明等特殊的属性):

    /// <summary>
            /// 查询表名
            /// </summary>
            /// <param name="t"></param>
            /// <returns></returns>
            private static string GetTableName(Type t)
            {
                string Name = t.Name;
                object[] os = t.GetCustomAttributes(typeof(TablNameAttribute), true);
                if (os.Length > 0)
                {
                    TablNameAttribute ta = os[0] as TablNameAttribute;
                    Name = ta.TableName;
                }
                return Name;
            }
    

      


    泛型反射是我们在做系统架构时需要经常用到的,如果能熟练应用到项目中可以对业务开发起到约束和管控的作用。












  • 相关阅读:
    uni-app在小程序开发者工具:TypeError: Cannot read property ‘forceUpdate‘ of undefined
    windows部署多个tomcat并添加到服务开机自动启动
    区域填充算法和多边形填充的扫描线算法[转]
    如何在不规则多边形内均匀撒点的算法[转]
    基于Living Atlas数据为木里山体滑坡敏感性建模【转】
    重磅!前端开发技术之Vue架构知识分享[转]
    如何使用 IAM 策略授予对特定 AWS S3 文件夹的用户特定访问权限?
    XXL-JOB安装、配置、启动、停止教程
    centos7 部署YApi
    CentOS 7安装MySQL8.0
  • 原文地址:https://www.cnblogs.com/DavidHuAtIT/p/12150003.html
Copyright © 2011-2022 走看看