我如何访问 myargument
价值 argvalue
从 ValidateMain
型号
[ValidateMain]
public class MainClass
{
[ValidateChild(myargument: "argvalue")]
public string myproperty { get; set; }
[ValidateChild(myargument: "argvalue2")]
public string myproperty2 { get; set; }
}
ValidationAttributes
public class ValidateChild : ValidationAttribute
{
private readonly string myargument;
public ValidateChild(string myargument)
{
this.myargument = myargument;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// Here I know how to get myargument value. My problem is how to get it in ValidateMain
return ValidationResult.Success;
}
}
public class ValidateMain : ValidationAttribute
{
public ValidateMain()
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
foreach (System.Reflection.PropertyInfo item in value.GetType().GetProperties())
{
// What I need here is to get 'myargument' value 'argvalue'
}
return ValidationResult.Success;
}
}
使用下面的语句来获取它的值。
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
foreach (System.Reflection.PropertyInfo item in value.GetType().GetProperties())
{
var x = item.CustomAttributes.FirstOrDefault().ConstructorArguments.FirstOrDefault();
}
return ValidationResult.Success;
}
调试并快速观看 然后你就可以知道如何获得它了