如何为多个BO属性定义IDataErrorInfo错误属性我开始通过IDataErrorInfo接口在我的WPF项目中实现验证。我的业务对象包含多个带有身份验证信息的属性。如何获取与此对象关联的所有错误消息的列表。我的想法是,这就是Error属性的用途,但我无法找到任何使用它来报告多个属性的人。谢谢!publicstringthis[stringproperty]{get{stringmsg=null;switch(property){case"LastName":if(string.IsNullOrEmpty(LastName))msg??="需要姓氏";休息;case"FirstName":if(string.IsNullOrEmpty(LastName))msg??="需要名字";休息;默认值:抛出新的ArgumentException(“无法识别的属性:”+property);}返回消息;}}publicstringError{get{returnnull;}}是的,我知道在哪里可以使用索引器。我想,这不是一个坏方法。我真正关注的是“错误”属性。我喜欢在业务对象中包含错误的概念。我不认为我正在尝试做的事情本身存在,所以我只是在对象上创建了一个错误字典(在属性发生时更新)并让Error返回一个CarriageReturn分隔的错误列表,如下所示:publicstringthis[字符串属性]{get{stringmsg=null;switch(property){case"LastName":if(string.IsNullOrEmpty(LastName))msg??="需要姓氏";休息;case"FirstName":if(string.IsNullOrEmpty(FirstName))msg??="需要名字";休息;默认值:抛出新的ArgumentException(“无法识别的属性:”+property);}if(msg!=null&&!errorCollection.ContainsKey(property))errorCollection。添加(属性,消息);如果(msg==null&&errorCollection.ContainsKey(property))errorCollection.Remove(property);返回消息;}}publicstringError{get{if(errorCollection.Count==0)returnnull;StringBuildererrorList=newStringBuilder();varerrorMessages=errorCollection.Values.GetEnumerator();while(errorMessages.MoveNext())errorList.AppendLine(errorMessages.Current);返回errorList.ToString();我认为使用验证属性要容易得多。classMyBusinessObject{[Required(ErrorMessage="Mustentercustomer")]publicstringCustomer{get;放;}[Range(10,99,ErrorMessage="价格必须在10到99"之间")]publicdecimalPrice{get;放;}//我还创建了一些自定义属性,例如验证路径[File(FileValidation.IsDirectory,ErrorMessage="Mustenteranimportfolder")]publicstringImportFolder{get;放;}publicstringthis[stringcolumnName]{returnInputValidation.Validate(this,columnName);}publicICollectionAllErrors(){返回InputValidation.Validate(this);}}辅助类InputValidation如下所示internalstaticclassInputValidationwhereT:IDataErrorInfo{//////验证源中的单个列/////////通常从IErrorDataInfo.this[]调用///要验证的实例///要验证的列的名称///由换行符或字符串分隔的错误消息。如果没有错误,则为空publicstaticstringValidate(Tsource,stringcolumnName){KeyValuePair,ValidationAttribute[]>验证器;if(mAllValidators.TryGetValue(columnName,outvalidators)){varvalue=validators.Key(source);varerrors=validators.Value.Where(v=>!v.IsValid(value)).Select(v=>v.ErrorMessage??"").ToArray();返回string.Join(Environment.NewLine,errors);}返回字符串。空;}//////验证源中的所有列//////要验证的实例///所有错误消息的列表。如果没有错误则为空列表publicstaticICollectionValidate(Tsource){Listmessages=newList();foreach(mAllValidators.Values中的var验证器){varvalue=validators.Key(source);messages.AddRange(validators.Value.Where(v=>!v.IsValid(value)).Select(v=>v.ErrorMessage??""));}返回消息;}//////获取属性的所有验证属性/////////privatestaticValidationAttribute[]GetValidations(PropertyInfoproperty){return(ValidationAttribute[])property.GetCustomAttributes(typeof(ValidationAttribute),trUE);}//////创建一个lambda来接收属性值/////////privatestaticFuncCreateValueGetter(PropertyInfoproperty){varinstance=Expression.Parameter(typeof(T),"i");varcast=Expression.TypeAs(Expression.Property(实例,属性),typeof(object));返回(Func)Expression.Lambda(cast,instance).Compile();}privatestaticreadonlyDictionary,ValidationAttribute[]>>mAllValidators;staticInputValidation(){mAllValidators=newDictionary,ValidationAttribute[]>>();foreach(varpropertyintypeof(T).GetProperties()){varvalidations=GetValidations(property);如果(validations.Length>0)mAllValidators.Add(property.Name,newKeyValuePair,ValidationAttribute[]>(CreateValueGetter(property),validations));我的理解是,要使用此接口,您需要枚举对象的属性,并为每个属性调用一次索引器,调用者有责任汇总任何错误消息。以上就是C#学习教程:如何为多个BO属性定义IDataErrorInfo错误属性。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处:
