博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用反射、特性简化代码
阅读量:4660 次
发布时间:2019-06-09

本文共 3958 字,大约阅读时间需要 13 分钟。

假设现在有一个学生类(Student)

///     /// 学生类    ///     public class Student    {           ///         /// 名字        ///         private string name;        public string Name        {            get { return name; }            set { name = value; }        }        ///         /// 年龄        ///         public int Age { get; set; }        ///         /// 地址        ///         public string Address { get; set; }        ///         /// 性别        ///         public string Sex;    }

如果需要判断某些字段(属性)是否为空,是否大于0,便有以下代码:

public static string ValidateStudent(Student student)        {            StringBuilder validateMessage = new StringBuilder();            if (string.IsNullOrEmpty(student.Name))            {                validateMessage.Append("名字不能为空");            }            if (string.IsNullOrEmpty(student.Sex))            {                validateMessage.Append("性别不能为空");            }            if (student.Age <= 0)            {                validateMessage.Append("年龄必填大于0");            }            //...... 几百行            // 写到这里发现不对啊,如果必填项有20多个,难道我要一直这样写吗!            return validateMessage.ToString();        }

这样的代码,重用性不高,而且效率低。

我们可以用特性,反射,然后遍历属性并检查特性。

首先自定义一个【必填】特性类,继承自Attribute

///     /// 【必填】特性,继承自Attribute    ///     public sealed class RequireAttribute : Attribute    {        private bool isRequire;        public bool IsRequire        {            get { return isRequire; }        }        ///         /// 构造函数        ///         ///         public RequireAttribute(bool isRequire)        {            this.isRequire = isRequire;        }    }

然后用这个自定义的特性标记学生类的成员属性:

///     /// 学生类    ///     public class Student    {           ///         /// 名字        ///         private string name;        [Require(true)]        public string Name        {            get { return name; }            set { name = value; }        }        ///         /// 年龄        ///         [Require(true)]        public int Age { get; set; }        ///         /// 地址        ///         [Require(false)]        public string Address { get; set; }        ///         /// 性别        ///         [Require(true)]         public string Sex;    }

通过特性检查类的属性:

///         /// 检查方法,支持泛型        ///         /// 
/// ///
public static string CheckRequire
(T instance) { var validateMsg = new StringBuilder(); //获取T类的属性 Type t = typeof (T); var propertyInfos = t.GetProperties(); //遍历属性 foreach (var propertyInfo in propertyInfos) { //检查属性是否标记了特性 RequireAttribute attribute = (RequireAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof (RequireAttribute)); //没标记,直接跳过 if (attribute == null) { continue; } //获取属性的数据类型 var type = propertyInfo.PropertyType.ToString().ToLower(); //获取该属性的值 var value = propertyInfo.GetValue(instance); if (type.Contains("system.string")) { if (string.IsNullOrEmpty((string) value) && attribute.IsRequire) validateMsg.Append(propertyInfo.Name).Append("不能为空").Append(","); } else if (type.Contains("system.int")) { if ((int) value == 0 && attribute.IsRequire) validateMsg.Append(propertyInfo.Name).Append("必须大于0").Append(","); } } return validateMsg.ToString(); }

执行验证:

static void Main(string[] args)        {            var obj = new Student()            {                Name = ""            };            Console.WriteLine(CheckRequire(obj));            Console.Read();        }

结果输出:

有人会发现,Sex也标记了[Require(true)],为什么没有验证信息,这是因为,Sex没有实现属性{ get; set; },GetProperties是获取不到的。

 

转载于:https://www.cnblogs.com/zhuyongblogs/p/5169054.html

你可能感兴趣的文章
python面向对象实例
查看>>
java基础之 创建对象的几种方式
查看>>
[HNOI2008]明明的烦恼
查看>>
Navicat不能连接linux数据库问题
查看>>
centos7关闭防火墙
查看>>
《C#高级编程》 读书笔记 -索引
查看>>
session cookie原理及应用
查看>>
ID3算法详解
查看>>
BZOJ1925: [Sdoi2010]地精部落
查看>>
学习进度条第十一周
查看>>
linux常用命令
查看>>
设置SQL PLUS环境
查看>>
关于虚拟机VM
查看>>
eclipse、tomca和jvm的相关内存配置
查看>>
python的迭代器
查看>>
spy memcached spring demo
查看>>
Python基础语法
查看>>
4.1.1 硬币游戏
查看>>
获取服务器信息
查看>>
JavaScript_5_对象
查看>>