假定如今有一个门生类(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 <= 0) { validateMessage.Append("岁数必填大于0"); } //...... 几百行 // 写到这里发明不对啊,假如必填项有20多个,岂非我要一向如许写吗! return validateMessage.ToString(); }
如许的代码,重用性不高,而且效力低。
我们可以用特征,反射,然后遍历属性并搜检特征。
起首自定义一个【必填】特征类,继续自Attribute
/// <summary> /// 【必填】特征,继续自Attribute /// </summary> public sealed class RequireAttribute : Attribute { private bool isRequire; public bool IsRequire { get { return isRequire; } } /// <summary> /// 组织函数 /// </summary> /// <param name="isRequire"></param> public RequireAttribute(bool isRequire) { this.isRequire = isRequire; } }
然后用这个自定义的特征标记门生类的成员属性:
/// <summary> /// 门生类 /// </summary> public class Student { /// <summary> /// 名字 /// </summary> private string name; [Require(true)] public string Name { get { return name; } set { name = value; } } /// <summary> /// 岁数 /// </summary> [Require(true)] public int Age { get; set; } /// <summary> /// 地点 /// </summary> [Require(false)] public string Address { get; set; } /// <summary> /// 性别 /// </summary> [Require(true)] public string Sex; }
经由过程特征搜检类的属性:
/// <summary> /// 搜检要领,支撑泛型 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance"></param> /// <returns></returns> public static string CheckRequire<T>(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#中运用反射以及特征简化的实例代码的细致内容,更多请关注ki4网别的相干文章!