Ejemplo n.º 1
0
        /// <summary>
        /// 检查
        /// </summary>
        public static void Check <T>(T item) where T : class
        {
            List <PropertyInfo> propertyInfos = item.GetType().GetProperties().Where(e => e.GetCustomAttributes <RequisiteAttribute>().Any()).ToList();

            if (propertyInfos != null && propertyInfos.Count > 0)
            {
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    RequisiteAttribute requisite = propertyInfo.GetCustomAttributes <RequisiteAttribute>().FirstOrDefault();
                    if (!requisite.CheckValueType)
                    {
                        if (propertyInfo.PropertyType.IsValueType)
                        {
                            continue;                                       // 值类型跳过
                        }
                    }
                    dynamic defaultValue = propertyInfo.PropertyType.IsValueType ? Activator.CreateInstance(propertyInfo.PropertyType) : null;
                    dynamic value        = propertyInfo.GetValue(item);
                    if (value == defaultValue)
                    {
                        if (requisite != null && !string.IsNullOrEmpty(requisite.Describe))
                        {
                            throw new FormatException($"{propertyInfo.Name}为必填字段。必填原因为:{requisite.Describe}");
                        }
                        else
                        {
                            throw new FormatException($"{propertyInfo.Name}为必填字段");
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// 比填字段检查
 /// </summary>
 /// <typeparam name="T">检查对象</typeparam>
 /// <param name="source">检查数据</param>
 public static void RequisiteCheck <T>(this T source) where T : class
 {
     RequisiteAttribute.Check <T>(source);
 }