使用Expression 对成员Validation

本文探讨了在C#中通过属性和表达式树实现学生对象的验证过程,包括年龄、姓名和父属性的检查。
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;

namespace ConsoleApplication1
{
   internal class Program
   {
      private static void Main()
      {

         var student = new Student { Age = 15 };
         var p = new Parent { Role = "", Sex = "Male" };
         student.TheParent = p;
         student.Validate(s => s.Age, s => s.Name);

         student.Validate();
         Console.Read();
      }
   }


   public class Parent
   {
      public string Role { get; set; }
      public string Sex { get; set; }
   }

   public class Student
   {
      public Student()
      {
         BuildValidationMethods();
      }

      public int Age { get; set; }
      public string Name { get; set; }
      public Parent TheParent { get; set; }

      public void Validate(params Expression<Func<Student, object>>[] expression)
      {
         foreach (var expr in expression)
         {
            string proName = string.Empty;
            var unaryExpresson = expr.Body as UnaryExpression;
            if (unaryExpresson != null)
            {
               proName = (unaryExpresson.Operand as MemberExpression).Member.Name;
            }
            else
            {
               proName = ((MemberExpression)expr.Body).Member.Name;
            }

            Validate(proName);
         }

      }
      private readonly IDictionary<object, Action> _validateMethods = new Dictionary<object, Action>();
      public void Validate(string proName)
      {
         _validateMethods[proName]();
      }

      private string ExpressionToString<TProperty>(Expression<Func<Student, TProperty>> expression)
      {
         return ((MemberExpression)expression.Body).Member.Name;
      }

      public void BuildValidationMethods()
      {
         _validateMethods.Add(ExpressionToString(s=>s.Age), () => Console.WriteLine(Age < 18 ? "teen-agers" : "adult"));
         _validateMethods.Add(ExpressionToString(s=>Name), () =>
            {
               if (String.IsNullOrEmpty(Name))
                  Console.WriteLine("Name is empty");
            });
         _validateMethods.Add(ExpressionToString(s=>s.TheParent.Role), () =>
            {
               if (string.IsNullOrEmpty(TheParent.Role))
               {
                  Console.WriteLine("Role is empty");
               }
            });
      }


      public void Validate()
      {
         foreach (var validateMethod in _validateMethods.Values)
         {
            validateMethod();
         }
      }
   }
}

 

转载于:https://www.cnblogs.com/shineqiujuan/archive/2013/02/01/2888889.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值