C# WebApi 根據實體類檢查傳參或字典檢查參數


 

根據實體類或字典檢查傳參,是否缺少參數並返回缺少參數

值類型必須聲明可空

 /// <summary>
    /// 自動處理屬性(當傳參屬性和實體類屬性一樣時可用)
    /// </summary>
    public static class EntityProperties
    {
        /// <summary>
        /// 根據 Dictionary<string, string> 得到實體類的字段名稱和值
        /// </summary>
        /// <typeparam name="T">實體類</typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetProperties<T>(T t)
        {
            var ret = new Dictionary<string, string>();

            if (t == null)
            {
                return null;
            }
            var properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

            if (properties.Length <= 0)
            {
                return null;
            }
            foreach (var item in properties)
            {
                var name = item.Name;                                                  //實體類字段名稱
                var value = Convert.ToString(item.GetValue(t, null));                //該字段的值

                if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                {
                    ret.Add(name, value);        //在此可轉換value的類型
                }
            }

            return ret;
        }

        /// <summary>
        /// 獲取實體類屬性返回List列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static List<string> GetPropertiesToList<T>(T t)
        {
            List<string> srtList = new List<string>();
            if (t == null)
            {
                return null;
            }
            var properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            //properties[0].PropertyType.
            foreach (var item in properties)
            {

                if (isType(item))
                {
                    bool bo = item.GetType().IsGenericType;
                    /*
               *這種也可以但必須對程序集有引用
               * var cType = Type.GetType(classname + "," + dllName);//類名完整路徑+程序集名稱
               */
                    var className = "";
                    var dllName = System.IO.Path.GetFileNameWithoutExtension(item.Module.Name);//獲取程序集名稱
                    if (item.PropertyType.IsGenericType)
                    {
                        var rgx = new Regex(@"(?i)(?<=\[)(.*)(?=\])");//中括號[]
                        var typeName = item.GetMethod.ReturnType.FullName;
                        var tmp = rgx.Match(typeName).Value;//中括號[]
                        var tmpArray = rgx.Match(tmp).Value.Split(',');
                        className = tmpArray[0];//獲取類名
                    }
                    else
                    {
                        className = item.PropertyType.FullName;//獲取類名
                    }

                    var asmb = Assembly.Load(dllName);//加載程序集
                    var type = asmb.GetType(className ?? throw new InvalidOperationException("GetPropertiesToList方法中className獲取類名為空"));      // 通過類名獲取類的type類型
                    if (type != null)
                    {
                        var propertyInfos = type.GetProperties(BindingFlags.Instance | BindingFlags.Public |
                                                               BindingFlags.IgnoreCase);
                        srtList.AddRange(propertyInfos.Select(info => info.Name));
                    }
                }
                srtList.Add(item.Name);
            }
            return srtList;
            //return properties.Length <= 0 ? null : (from item in properties let name = item.Name where item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String") select name).ToList();
        }

        /// <summary>
        /// 根據Dictionary來設置實體類值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T SetProperties<T>(T t, Dictionary<string, string> d)
        {
            if (t == null || d == null)
            {
                return default(T);
            }
            var properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

            if (properties.Length <= 0)
            {
                return default(T);
            }
            foreach (var item in properties)
            {
                var name = item.Name;                                         //名稱
                var value = Convert.ToString(item.GetValue(t, null));       //
                if (!item.PropertyType.IsValueType && !item.PropertyType.Name.StartsWith("String")) continue;
                var val = d.FirstOrDefault(c => c.Key == name).Value;
                if (val == null || val == value) continue;
                if (item.PropertyType.Name.StartsWith("Nullable`1"))
                {
                    item.SetValue(t, Convert.ToDateTime(val), null);
                }
                else
                {
                    item.SetValue(t, val, null);
                }
            }

            return t;
        }

        /// <summary>
        /// 根據實體列表判斷參數
        /// </summary>
        /// <param name="parameterList">參數列表</param>
        /// <param name="entityList">實體列表</param>
        /// <returns></returns>
        public static List<string> IsPropertiesList(Dictionary<string, string> parameterList, List<string> entityList)
        {
            return entityList.Where(item => !parameterList.ContainsKey(item)).ToList();
        }

        /// <summary>
        /// 根據實體列表判斷參數
        /// </summary>
        /// <param name="parameterList">參數列表</param>
        /// <param name="entityList">實體列表</param>
        /// <returns></returns>
        public static string IsDictionaryProperties(Dictionary<string, string> parameterList, List<string> entityList)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in entityList.Where(item => !parameterList.ContainsKey(item)))
            {
                sb.AppendLine(item + ",");
            }
            return (sb.Length > 0
                   && !"null".Equals(sb.ToString())
                   && !"".Equals(sb.ToString())) ? sb.ToString().Trim() : null;
            //return entityList.Where(item => !parameterList.ContainsKey(item));
        }
        /// <summary>
        /// 實體參數檢查
        /// </summary>
        /// <typeparam name="T">接收參數的實體</typeparam>
        /// <param name="t">接收參數的實體</param>
        /// <param name="entityList">實體類</param>
        /// <param name="isfq">為false時只對列表循環一次</param>
        /// <returns></returns>
        public static string IsModelProperties<T>(T t, List<string> entityList,bool isfq=false)
        {
            var fq = 0;
            var sb = new StringBuilder();
            //var ret = new Dictionary<object, object>();
            if (t == null) { return null; }
            var properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            if (properties.Length <= 0) { return null; }

            foreach (PropertyInfo item in properties)
            {
                var name = item.Name;
                var value = item.GetValue(t, null);
                if (value!=null)
                {
                    if (value.GetType().IsGenericType)
                    {
                        //var typeList = typeof(List<>);
                        //Type typeDataList = typeList.MakeGenericType(typeof(DateTime));//通過List<>構建出List<DateTime>
                        if (!(value is ICollection list)) continue;
                        if (list.Count <= 0) continue;

                        foreach (var enItem in list)
                        {
                            
                            if (!isfq && fq>=1)
                            {
                                break;
                            }
                            fq++;
                            var modelEn = enItem.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

                            foreach (var elist in from elist in entityList
                                                  from va in modelEn
                                                  where va.Name.Equals(elist, StringComparison.OrdinalIgnoreCase)
                                                  let data = va.GetValue(enItem, null)
                                                  where data == null
                                                  select elist)
                            {
                                if (!sb.ToString().ToUpper().Contains(elist.ToUpper()))
                                {
                                    sb.AppendLine("屬性名稱:  " + elist + ",");
                                }
                            }

                            //foreach (var elist in entityList)
                            //{
                            //    foreach (var va in modelEn)
                            //    {
                            //        if (!va.Name.Equals(elist, StringComparison.OrdinalIgnoreCase)) continue;
                            //        var data = va.GetValue(enItem, null);
                            //        if (data == null)
                            //        {
                            //            sb.AppendLine(elist + ",");
                            //        }
                            //    }
                            //}
                        }
                    }
                    else
                    {
                        foreach (var elist in entityList)
                        {

                            var cou = properties.Where(n => n.Name == elist).ToList();
                            if (cou.Count > 0)
                            {
                                if (item.GetValue(t, null) != null) continue;
                                //存在等於空則添加
                                if (!sb.ToString().ToUpper().Contains(elist.ToUpper()))
                                {
                                    sb.AppendLine("屬性名稱:  " + elist + ",");
                                }

                            }
                            else
                            {
                                //不存在直接添加
                                if (!sb.ToString().ToUpper().Contains(elist.ToUpper()))
                                {
                                    sb.AppendLine("屬性名稱:  " + elist + ",");
                                }
                            }

                        }

                    }
                }
                else
                {
                    //不存在直接添加
                    if (!sb.ToString().ToUpper().Contains(name.ToUpper()))
                    {
                        sb.AppendLine("屬性名稱:  " + name + ",");
                    }
                }
               
            }

            return (sb.Length > 0
                    && !"null".Equals(sb.ToString())
                    && !"".Equals(sb.ToString())) ? sb.ToString().Trim() : null;

        }

        /// <summary>
        /// object轉實體
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listObj"></param>
        /// <returns></returns>
        private static List<T> PraseList<T>(object listObj)
        {
            List<T> result = new List<T>();
            if (!listObj.GetType().IsGenericType)
                throw new Exception("非集合類型");
            if (listObj as System.Collections.ICollection != null)
            {
                var list = (System.Collections.ICollection)listObj;
                if (list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        result.Add((T)item);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// Type傳參轉換成泛型T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="inValue"></param>
        /// <returns></returns>
        public static T GetValue<T>(string inValue)
        {
            //一般類型
            return (T)Convert.ChangeType(inValue, typeof(T));
        }

        /// <summary>
        /// 判斷是否常見值類型
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static bool isType(PropertyInfo item)
        {
            return !item.PropertyType.Name.StartsWith("string")
                   && !item.PropertyType.Name.StartsWith("int")
                   && !item.PropertyType.Name.StartsWith("double")
                   && !item.PropertyType.Name.StartsWith("Int32")
                   && !item.PropertyType.Name.StartsWith("Int64")
                   && !item.PropertyType.Name.StartsWith("IntPtr")
                   && !item.PropertyType.Name.StartsWith("DateTime")
                   && !item.PropertyType.Name.StartsWith("bool");
        }

    }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM