c# Reflection 反射 简单示例

c# Reflection 反射 简单示例,做小程序时用到了数据库,就随便写的一个通过对象属性成员生成 sql字符串的一个基类,
只是为了满足demo功能所写并不完善,留做笔记,方便日后再次需要时方便查阅。

    public class ModelBase
    {


        public string BuildWhere(string[] fields, string logic = " and ")
        {

            string strs = "";

            Type type = this.GetType();

            PropertyInfo[] pros = type.GetProperties();
            foreach (PropertyInfo proinfo in pros)
            {
                if (fields == null)
                {
                    string propeval = GetVal(proinfo);
                    if ( string.IsNullOrEmpty( propeval)) {
                        continue;
                    }


                    strs += logic;

                    strs += string.Format(" {0} like '%{1}%' ", proinfo.Name.ToLower(), propeval);
                    continue;
                }

                if (fields.Contains(proinfo.Name) || fields.Contains(proinfo.Name.ToLower()))
                {

                    string propeval = GetVal(proinfo);
                    if (string.IsNullOrEmpty(propeval))
                    {
                        continue;
                    }

                  
                    strs += logic ;
                    
                    strs += string.Format(" {0} like '%{1}%' ", proinfo.Name.ToLower(), propeval);
                }
            }
            
            return strs;
        }

        public String BuildUpdate(string[] fields,string where = "") {
            string strs = "";
            
            Type type = this.GetType();

            PropertyInfo[] pros = type.GetProperties();
            foreach (PropertyInfo proinfo in pros) {
                if ((proinfo.Name.Equals("Id") || proinfo.Name.Equals("id")) 
                    && where .Equals("")) {
                    string idval = Convert.ToString( proinfo.GetValue(this,null));
                    where = string.Format(" id = '{0}' ",idval);
                    continue;
                }
                if (fields == null) {
                    string propeval = GetVal(proinfo);

                    if (!strs.Equals(""))
                    {
                        strs += ",";
                    }
                    strs += string.Format(" {0}= '{1}' ", proinfo.Name.ToLower(), propeval);
                    continue;
                }


                if (fields.Contains(proinfo.Name) || fields.Contains( proinfo.Name.ToLower())) {

                    string propeval = GetVal(proinfo);
                     
                    if (!strs.Equals("")) {
                        strs += ",";
                    }
                    strs += string.Format( " {0}= '{1}' ",proinfo.Name.ToLower(),propeval);
                }
            }
            if (strs == "") {
                throw new Exception("未找到任何对应属性"); 
            }
            string tablename =  type.Name.Replace("Model","").ToLower(); ;
            strs = string.Format( " update [{0}] set {1} where {2}",tablename, strs ,where ); 
            return strs;
        }

        public String BuildAdd(string[] fields = null) {
            string strs = "";
            string fieldstr = "";
            string valstr = "";
            Type type = this.GetType();

            PropertyInfo[] pros = type.GetProperties();
            foreach (PropertyInfo proinfo in pros)
            {

                if ((proinfo.Name.Equals("Id") || proinfo.Name.Equals("id"))
                    )
                {
                    continue;
                }
                if (fields == null) {
                    string propeval = GetVal(proinfo);
                    if (!fieldstr.Equals(""))
                    {
                        fieldstr += ",";
                        valstr += ",";
                    }
                    fieldstr += proinfo.Name.ToLower() ;
                    valstr += string.Format("'{0}'",  propeval);
                    continue;
                }

                if (fields.Contains(proinfo.Name) || fields.Contains(proinfo.Name.ToLower()))
                {
                    string propeval = GetVal(proinfo);
                    if (!fieldstr.Equals(""))
                    {
                        fieldstr += ",";
                        valstr += ",";
                    }
                    fieldstr += proinfo.Name.ToLower();
                    valstr += string.Format("'{0}'", propeval);
                }
            }
            if (fieldstr == "")
            {
                throw new Exception("未找到任何对应属性");
            }
            string tablename = type.Name.Replace("Model", "").ToLower();
            strs = string.Format( " insert into [{0}] ({1}) values({2}) ",tablename,fieldstr,valstr);

            return strs;
        }

        public void RowToModel(DataRow row)
        {
            Type type = this.GetType();
            PropertyInfo[] pros = type.GetProperties();
            foreach (PropertyInfo proinfo in pros)
            {
                if (row.Table.Columns.Contains(proinfo.Name.ToLower()))
                {

                    if (proinfo.PropertyType == typeof(DateTime))
                    {
                        DateTime dt;
                        DateTime.TryParse(row[proinfo.Name.ToLower()].ToString(), out dt);
                        proinfo.SetValue(this, dt, null);
                    }
                    else if (proinfo.PropertyType == typeof(int))
                    {
                        int intval;
                        int.TryParse(row[proinfo.Name.ToLower()].ToString(), out intval);
                        proinfo.SetValue(this, intval, null);
                    }
                    else if (proinfo.PropertyType == typeof(long))
                    {
                        long longval;
                        long.TryParse(row[proinfo.Name.ToLower()].ToString(), out longval);
                        proinfo.SetValue(this, longval, null);
                    }
                    else if (proinfo.PropertyType == typeof(float))
                    {
                        float floatval;
                        float.TryParse(row[proinfo.Name.ToLower()].ToString(), out floatval);
                        proinfo.SetValue(this, floatval, null);
                    }
                    else if (proinfo.PropertyType == typeof(double))
                    {
                        double doubleval;
                        double.TryParse(row[proinfo.Name.ToLower()].ToString(), out doubleval);
                        proinfo.SetValue(this, doubleval, null);
                    }
                    else if (proinfo.PropertyType == typeof(MonitorState))
                    {
                        MonitorState msval = MonitorState.Normal;
                        MonitorState.TryParse(row[proinfo.Name.ToLower()].ToString(), out msval);
                        proinfo.SetValue(this, msval, null);
                    }
                    else {
                        proinfo.SetValue(this, row[proinfo.Name.ToLower()].ToString(), null);
                    }
                }
            }
        }

        private string GetVal(PropertyInfo proinfo) {

            string propeval = "";
            if (proinfo.PropertyType == typeof(DateTime))
            {

                DateTime dt = Convert.ToDateTime(proinfo.GetValue(this, null));
                propeval = dt.ToString();
            } else if (proinfo.PropertyType == typeof(MonitorState))
            {
                MonitorState ms = MonitorState.Normal;
                MonitorState.TryParse(proinfo.GetValue(this, null).ToString(),out ms);
                propeval = Convert.ToString((int)ms);
            }

            else
            {
                propeval = Convert.ToString(proinfo.GetValue(this, null));
            }
            return propeval;
        }




    }
}

发表评论

您的电子邮箱地址不会被公开。