Into the garden for more than three years, and never just look at the articles of the Great God, and did not write, today, a whim to write an article, my level is slightly shallow, do not take offense, big God do not spray
First, define a validation type enumeration, which lists only the simplest two types of validation
1 /// <summary>2 ///validation Type Enumeration3 /// </summary>4 Public enumValidatetype5 {6 /// <summary>7 ///non-null validation8 /// </summary>9 Notnullvalidate,Ten /// <summary> One ///non-null validation A /// </summary> - notnulloremptyvalidate -}
The validation method corresponding to each validation type is then defined, and the method name corresponding to the validation type is consistent
1 /// <summary>2 ///non-null validation3 /// </summary>4 /// <param name= "value" ></param>5 /// <returns></returns>6 Public Static BOOLNotnullvalidate (Objectvalue)7 {8 if(Value isDBNull)9 return false;Ten returnValue = =NULL?false:true; One } A - /// <summary> - ///non-null validation the /// </summary> - /// <param name= "value" ></param> - /// <returns></returns> - Public Static BOOLNotnulloremptyvalidate (Objectvalue) + { - if(Value isDBNull) + return false; A if(Value = =NULL) at return false; - return string. IsNullOrEmpty (value. ToString ())?false:true; -}
When the method is defined, it is called, and here I write a generic calling method
1 /// <summary>2 ///validating the object value3 /// </summary>4 /// <param name= "value" ></param>5 /// <param name= "Validatetype" ></param>6 /// <returns></returns>7 Public Static BOOLValidateobject (Objectvalue,validatetype Validatetype)8 {9Validateutil validateobj=Newvalidateutil ();Ten One //validation method corresponding to the validation type of the reflection get AMethodInfo method =Validateobj.gettype (). GetMethod (Validatetype.tostring ()); - if(Method = =NULL) - Throw NewException ("the validation method corresponding to this validation type was not found:"+validatetype.tostring ()); the - return(BOOL) method. Invoke (Validateobj,New Object[] {value}); -}
On this basis I expanded the validation of an entity class
1 /// <summary>2 ///validating some fields in an entity class3 /// </summary>4 /// <param name= "objentity" >entity class</param>5 /// <param name= "Validatefields" >dictionaty field names to validate, validation type enumeration</param>6 /// <returns></returns>7 Public Static BOOLValidateentity (Objectobjentity,dictionary<string,validatetype>validatefields)8 {9Propertyinfo[] Property =Objentity.gettype (). GetProperties ();Ten foreach(PropertyInfo FieldinchProperty ) One { A ObjectValue = field. GetValue (Objentity,NULL); - - if(Validatefields! =NULL&&validatefields.containskey (field. Name)) the if(!Validateutil.validateobject (value, Validatefields[field. Name])) - Throw NewException (field. Name +":"+validatefields[field. Name]. ToString () +"validation failed! "); - } - return true; +}
I'm done here, thanks.
Implementation of a simple generic validation class