Ken H

Ken H

  • NA
  • 646
  • 354.6k

parameters validation by custom attributes in c#

Mar 9 2015 12:05 AM
Hello friend,
 
   I try to use the attribute to verify the parameters of the client.
  Now, how to use the interface injection to verify?
 
public interface ICheckParameter{
void Check(object objValue, string parameterName);
}
[AttributeUsage(AttributeTargets.Parameter)]
public class CheckIsNullOrEmptyAttribute : Attribute,ICheckParameter{
public CheckIsNullOrEmptyAttribute(){}
public void Check(object objValue,string parameterName){
if (objValue == null) throw new ArgumentNullException(parameterName);
}
}
[AttributeUsage(AttributeTargets.Parameter)]
public class CheckLengthAttribute : Attribute,ICheckParameter {
private int _minValue;
private int _maxValue;
public CheckLengthAttribute(int minValue,int maxValue){
this._minValue=minValue;
this._maxValue=maxValue;
}
public void Check(object objValue, string parameterName){
if (objValue == null) throw new ArgumentNullException(parameterName, "The object can't be null.");
int len = objValue.ToString().Length;
if (len<this._minValue||len>this._maxValue)
throw new ArgumentOutOfRangeException(parameterName,
string.Format("The value length must be between {0} and {1}",
this._minValue,this._maxValue));
}
}
public interface ICheckPower{
void CheckPower([CheckIsNullOrEmpty]string uName, [CheckLength(6, 10)]string pwd);
}
public class LoginClass : ICheckPower {
public LoginClass() { }
public void CheckPower(string uName, string pwd) {
try{
Console.WriteLine("Pass...\n");
}
catch (Exception error)
{
Console.WriteLine("An Error:{0}\n",error.Message);
}
}
}
class Program {
static void Main(string[] args){
LoginClass lc = new LoginClass();
lc.CheckPower(null, "123456");
lc.CheckPower("Test", "123");
Console.ReadKey(true);
}
}
 
 
Thank.  :) 

Answers (2)