C#通过特性的方式去校验指定数据是否为空

1.特性定义

    [AttributeUsage(AttributeTargets.Property)]
    public class VerificationAttribute : Attribute
    {
        public bool IsEmpty => true;
        public VerificationAttribute()
        {
        }
    }

2.定义在属性上

        /// 
        /// 域名
        /// 
        [Verification]
        public string FieldName { get; set; } = "FIELD_NAME";

        /// 
        /// 值名
        /// 
        [Verification]
        public string FieldValue { get; set; } = "FIELD_VAL";

3.基类实现,通过特性的方式去校验指定数据是否为空,判断list是否为空

    protected bool CanSave()
        {
            Type property = Setting.GetType();
            var list = property.GetProperties().ToList();
            foreach (var item in list)
            {
                VerificationAttribute? attribute = (VerificationAttribute?)item.GetCustomAttribute(typeof(VerificationAttribute));
                if (attribute != null)
                {
                    var proValue = item.GetValue(Setting);
                    if (proValue == null)
                        return false;
                    else if (item.PropertyType == typeof(string))
                    {
                        if (string.IsNullOrEmpty(proValue.ToString()?.Trim()))
                            return false;
                    }
                    else if (item.PropertyType == typeof(bool))
                    {
                        if (!(bool)proValue)
                            return false;
                    }
                    else if (typeof(IEnumerable).IsAssignableFrom(item.PropertyType))
                    {
                        IEnumerable<object>? enumerable = proValue as IEnumerable<object>;
                        if (enumerable == null)
                            return false;
                        if (!enumerable.Any())
                            return false;
                    }
                    else
                        return false;
                }
            }

            return true;
        }

你可能感兴趣的:(c#,开发语言)