使用Expression 对成员Validation

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();
         }
      }
   }
}

 

posted @ 2013-02-01 13:40  chunchill  阅读(232)  评论(0编辑  收藏  举报