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 (lenthis._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. :)

VulpesPosted Mar 9, 2015, 5:28 PM
// add using directive
using System.Reflection;
// add some lines to CheckPower method
The output now should be:
Ken HPosted Mar 9, 2015, 9:28 PM