假设现在有一个学生类(Student)
- { { name = Age { ; Address { ;
登录后复制
如果需要判断某些字段(属性)是否为空,是否大于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
这样的代码,重用性不高,而且效率低。
我们可以用特性,反射,然后遍历属性并检查特性。
首先自定义一个【必填】特性类,继承自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是获取不到的
以上就是C#中使用反射以及特性简化的实例代码的详细内容,更多请关注【创想鸟】其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。