IDataErrorInfo vs ValidationRule vs Exception [英] IDataErrorInfo vs ValidationRule vs Exception

查看:89
本文介绍了IDataErrorInfo vs ValidationRule vs Exception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我哪种是WPF中验证的更好方法.

Can anyone tell me which is a better approach for Validation in WPF.

  1. 实现IDataErrorInfo
  2. 创建ValidationRule
  3. 引发异常

在性能,内存泄漏,代码可维护性和重用性方面.

in terms of performance, memory leaks, code maintainability and re-use.

推荐答案

这是一个复杂的请求,说实话,它可能会根据喜好而有所不同.但是,这是我的理解:

This is kind of a complex request, and honestly it'll probably vary based on preference more than anything else. But, here's my understanding:

  • 性能:除非您的其他实现令人恐惧,否则几乎每次都将丢失异常.投掷/接球周期有大量开销. (轶事:我有一个必须是数字"检查,这是一个例外,当它失败时,它会滞后" UI一段明显的时间,但是当转换为ValidationRule时,它实际上是即时的.)
  • 内存泄漏:这取决于验证规则或IDataErrorInfo实现的完成方式.
  • 代码可维护性,重用:当然,这是有趣的部分.您真正应该问的是什么时候使用ValidationRule代替IDataErrorInfo或反之亦然?"
  • Performance: Exceptions will lose nearly every time unless your other implementations are horrendous. There's significant overhead to the throw/catch cycle. (Anecdote: I had a 'must be a number' check that was an exception, it "lagged" the UI for a noticeable time when it failed, but when converted to a ValidationRule it was effectively instant.)
  • Memory leaks: This depends on how your validation rules or IDataErrorInfo implementations are done.
  • Code maintanability, reuse: This is the interesting part, of course. What you really should be asking is "when is it appropriate to use a ValidationRule instead of IDataErrorInfo or vice versa?"

ValidationRules比IDataErrorInfo早(我相信后者是在.Net 3.5中引入的).仅基于此,WPF团队似乎更喜欢IDataErrorInfo.但事实是,它们是为不同的事物而构建的.如果您具有MVVM或等效模式,则IDataErrorInfo对于模型中的错误(例如负年龄)比较有效,而ValidationRules对于 view 中的错误更有效(例如,年龄为☃).当然,可以使ValidationRules执行业务逻辑"检查,或者让IDataErrorInfo告诉您一个unicode雪人不是有效年龄",但是(通过这种方式)您(可能)将获得最佳的可维护性.

ValidationRules are older than IDataErrorInfo (I believe the latter was introduced in .Net 3.5). Based on this alone, it would seem that the WPF team prefers IDataErrorInfo. But the truth is they're built for different things. If you have MVVM or an equivalent pattern, IDataErrorInfo is superior for errors in the model (like, say, a negative age) whereas ValidationRules are superior for errors in the view (say, an age of ☃). It's of course possible to have the ValidationRules perform "business logic" checks, or to have the IDataErrorInfo tell you "a unicode snowman is not a valid age", but you'll (probably) get the best maintainability by keeping to this pattern.

但是在初始测试之后,请不要使用异常进行验证,以查看应该测试的确切条件.

But don't use exceptions for validation beyond the initial testing to see what exact conditions you should be testing for.

这篇关于IDataErrorInfo vs ValidationRule vs Exception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆