我正在寻找创建一个ValidationRule类来验证实体类型对象上的属性.我真的很想设置要检查的属性的名称,然后为该类提供一个委托或一个lambda表达式,当对象运行其IsValid()方法时将在运行时对其进行评估.是否有人有类似这样的代码片段,或者关于如何将匿名方法作为参数或属性传递的任何想法?
I'm looking to create an ValidationRule class that validates properties on an entity type object. I'd really like to set the name of the property to inspect, and then give the class a delegate or a lambda expression that will be evaluated at runtime when the object runs its IsValid() method. Does anyone have a snippet of something like this, or any ideas on how to pass an anonymous method as an argument or property?
此外,我不确定我是否在解释自己要完成的工作,因此,如果我不清楚,请提出问题.
Also, I'm not sure if I'm explaining what I'm trying to accomplish so please ask questions if I'm not being clear.
推荐答案实际上,您要使用的是Func<T,bool>,其中T是您要验证的商品的类型.然后你会做这样的事情
Really, what you want to use is Func<T,bool> where T is the type of the item you want to validate. Then you would do something like this
validator.AddValidation(item => (item.HasEnoughInformation() || item.IsEmpty());您可以将它们存储在List<Func<T,bool>>中.
you could store them in a List<Func<T,bool>>.
更多推荐
C#Lambda表达式或委托作为属性或参数
发布评论