我有一个使用自定义验证器的模型类,如下面的代码所示。
public class Model1
{
[ApplicationIdentifierValidator()]
public Guid ApplicationIdentifier { get; set; }
public string ApplicationName { get; set; }
public string ApplicationType { get; set; }
}
public class ApplicationIdentifierValidator: ValidationAttribute
{
public ApplicationIdentifierValidator() { }
protected override ValidationResult IsValid(object value, ValidationContext context)
{
Model1 model = (Model1)(context.ObjectInstance);
Guid ApplicationIdentifier = model.ApplicationIdentifier;
// Validate ApplicationIdentifier value
return ValidationResult.Success;
}
}
现在我添加了另一个需要使用相同验证器的模型类。
public class Model2
{
[ApplicationIdentifierValidator()]
public Guid ApplicationIdentifier { get; set; }
public Guid SystemIdentifier { get; set; }
}
问题是当在Model2的上下文中使用ApplicationIdentifierValidator时,它在转换为Model1时抛出异常
Model1 model = (Model1)(context.ObjectInstance);
任何想法可以更好地重用同一验证器吗?
答案 0 :(得分:1)
您可以使用继承。基本的OO设计应该满足您的确切需求。 通过让您的两个模型继承自ModelBase,您的验证代码可以将对象强制转换为ModelBase并使用共享属性。
abstract class ModelBase{
[ApplicationIdentifierValidator()]
public Guid ApplicationIdentifier { get; set; }
}
class Model1: ModelBase{
public string ApplicationName { get; set; }
public string ApplicationType { get; set; }
}
class Model2: ModelBaes{
public Guid SystemIdentifier { get; set; }
}
public class ApplicationIdentifierValidator: ValidationAttribute
{
public ApplicationIdentifierValidator() { }
protected override ValidationResult IsValid(object value, ValidationContext context)
{
ModelBase model = (ModelBase)(context.ObjectInstance);
Guid ApplicationIdentifier = model.ApplicationIdentifier;
// Validate ApplicationIdentifier value
return ValidationResult.Success;
}
}