必需如果项目存在于数组中

问题描述

我正在尝试创建一个自定义的 RequiredIf 属性,该属性需要基于数组中存在的字段。数组是模型的一部分,如下面的示例模型所示,FamilyHistoryCustomerItem 有一个字符串类型的字段。

public class FamilyHistory {

    [CanBeNull] public List<FamilyHistoryCustomerItem> FamilyHistoryCustomerItems { get; set; }

    [RequiredIfItemInCollection(FamilyHistoryCustomerItems,MedicalConditions.ColonOrBowelCancer)]
    public bool ColonOrBowelImmediateFamilyHadColonCancerHnpccOrLynchSyndrome { get; set; }
}

这是我创建的一个简单的自定义属性,当我尝试传递数组时,该属性会抛出错误,因为数组未初始化。这甚至可能吗,这是我第一次使用这些,所以请对我放轻松:)

public class RequiredIfItemInCollection : ValidationAttribute
    {
        private readonly string[] collection;
        private readonly string item;

        public RequiredIfItemInCollection(string[] items,string item)
        {
            if (items.IsNullOrEmpty() || item.IsNullOrEmpty())
                throw new ArgumentOutOfRangeException(nameof(items),"Nothing was provided");

            collection = items;
        }

        protected override ValidationResult IsValid(object value,ValidationContext validationContext)
        {
            return collection.Contains(item)
                    ? ValidationResult.Success
                    : new ValidationResult(this.ErrorMessage);
        }
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...