C#Lambda表达式或委托作为属性或参数

编程入门 行业动态 更新时间:2024-10-19 13:30:48
本文介绍了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表达式或委托作为属性或参数

本文发布于:2023-11-08 07:34:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568742.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   属性   参数   Lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!