C#Lambda表达式或委托作为属性或参数 [英] C# Lambda Expressions or Delegates as a Properties or Arguments

查看:119
本文介绍了C#Lambda表达式或委托作为属性或参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找创建一个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表达式或委托作为属性或参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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