我有一个像这样的自定义 ValidationAttribute :
public class ReceiverRegion : ValidationAttribute
{
private RegionService regionService;
private CityService cityService;
public ReceiverRegion() : base("Incorrect region code")
{
this.regionService = new RegionService();
this.cityService = new CityService();
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int regionId = Convert.ToInt32(value);
int plate = Convert.ToInt32((validationContext.ObjectInstance as CorporateOrderItem).ReceiverCity);
int productGroupId = Convert.ToInt32(validationContext.Items["productGroup"].ToString());
if (!CheckReceiverRegionExistence(regionId, plate, productGroupId))
{
IEnumerable regions = this.regionService.GetList(cityService.GetByPlate(plate).PKCityId);
return new CorporateOrderValidationResult(base.ErrorMessage, regions.Select(r=>r.Name));
}
return CorporateOrderValidationResult.Success;
}
private bool CheckReceiverRegionExistence(int plate, int regionId, int productGroup)
{
return !(regionService.GetByCityAndRegionIdForProductGroup(plate, regionId, productGroup) == null);
}
}
但正如您在 IsValid 方法中看到的那样,我试图返回一个继承自 ValidationResult 的自定义对象。我的问题是,我无法访问我的CorporateOrderValidationResult
实例的额外成员,因为 IsValid 返回基本 ValidationResult 类型。下面是我调用 validate 并获取 ValidationResult 集合作为返回值的代码。
List results = new List();
bool isValid = Validator.TryValidateObject(instance, context, results, true);
我尝试将 results 对象转换为List<CorporateOrderValidationResult>
,但无论我尝试什么(例如 -->item as CorporateOrderValidationResult
或者我得到 InvalidCastExceptionresults.OfType<CorporateOrderValidationResult>()
或(CorporateOrderValidationResult)item)
null 值。有没有可能的方法将此结果列表转换为我的自定义结果类的列表?谢谢...