陈程的技术博客

  • 关于作者
全栈软件工程师
一个专注于技术研究创新的程序员
  1. 首页
  2. .NET
  3. 正文

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

2023年9月21日 1124点热度 0人点赞 0条评论

1.特性定义

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

2.定义在属性上

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

/// <summary>
/// 值名
/// </summary>
[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;
      }

 

标签: 暂无
最后更新:2023年9月21日

博主

全栈工程师,侧重项目技术解决方案规划和开发

打赏 点赞
< 上一篇
下一篇 >

文章评论

取消回复

分类
  • .NET (65)
  • docker (3)
  • linux (12)
  • python (20)
  • web (14)
  • 小程序 (4)
  • 数据库 (2)
  • 未分类 (4)
  • 杂七杂八 (10)
标签聚合
centos DevExpress C# linux nginx js winform python
最新 热点 随机
最新 热点 随机
.NET开发手册标准参考 招募兼职前端开发 Centos安装dotnet6环境 VS上切换分支,vs编译运行出现bug,A fatal error was encountered彻底解决方案 用C#封装一个线程安全的缓存器,达到目标定时定量更新入库 C#通过特性的方式去校验指定数据是否为空
WTM部署CentOS验证码错误 H5+js写app时候解决怎么在锁屏和后台状态下执行 python快速把office文档execl或者word等转成pdf winfrom 解决PictureBox加载图片后不释放内存问题 fastapi做后台的跨域官方BUG以及修复方式 DreamSkin自定义美化控件-TreeView控件

COPYRIGHT © 2021 陈程的技术博客. ALL RIGHTS RESERVED.

THEME KRATOS MADE BY VTROIS