C#中的Action、Func和Predicate如何使用
前言
委托是一个类型安全的函数指针,它可以引用与委托具有相同签名的方法。委托常用于实现回调方法或者事件机制,在C#中一般用"delegate"关键字声明。你可以声明一个和类平级的委托,也可以嵌套在类中。
Func和Action是什么,如何使用?
两者最基本的区别是,前者适合那些需要带返回值的委托,后者适合那些不带返回值的委托。
Func所引用的方法接收一个或者多个入参并带有一个返回值,Action所引用的方法接收一个或者多个参数并且没有返回值,换句话说,你的委托所引用的方法没有返回值,这时候适合用Action。
Predicate所引用的方法接收一个或者多个泛型参数并且返回一个bool值,你可以假定它等价于Func
C#中使用Action
你可以使用委托去实现事件和回调方法,C#委托非常类似于C++中的函数指针,但是C#中的委托是类型安全的,你可以将方法作为参数传递给委托从而让委托指向该方法。
下面的代码片段展示了Action委托的语法结构。
Action
接下来的代码清单展示了如何使用Action委托,当下面的代码执行结束后会在控制台打印Hello!!!。
staticvoidMain(string[]args) { Actionaction=newAction (Display); action("Hello!!!"); Console.Read(); } staticvoidDisplay(stringmessage) { Console.WriteLine(message); }
C#中使用Func
现在我们一起学习下Func委托,下面是Func的语法结构。
Func
接下来的代码片段展示了如何在C#中使用Func委托,最终方法会打印出Hra(基本薪资的40%)的值,基本薪资是作为参数传下去的,如下代码所示:
staticvoidMain(string[]args) { Funcfunc=newFunc (CalculateHra); Console.WriteLine(func(50000)); Console.Read(); } staticdoubleCalculateHra(intbasic) { return(double)(basic*.4); }
值得注意的是,Func委托的第二个参数表示方法的返回值,在上面这个例子中,它就是计算后的Hra值,作为double型返回。
C#中使用Predicate
Predicate委托常用于检索collection,下面是Predicate的语法结构。
Predicate
值得注意的是,Predicate
考虑下面的Customer实体类。
classCustomer { publicintId{get;set;} publicstringFirstName{get;set;} publicstringLastName{get;set;} publicstringAddress{get;set;} publicstringCity{get;set;} publicstringState{get;set;} publicstringCountry{get;set;} }
接下来生成一个customer集合并且丢一些数据进去,如下代码:
ListcustList=newList (); custList.Add(newCustomer{Id=1,FirstName="Joydip",LastName="Kanjilal",State="Telengana",City="Hyderabad",Address="Begumpet",Country="India"}); custList.Add(newCustomer{Id=2,FirstName="Steve",LastName="Jones",State="OA",City="NewYork",Address="LakeAvenue",Country="US"});
接下来是完整的代码片段展示了如何使用Predicate去检索集合。
staticvoidMain(string[]args) { ListcustList=newList (); custList.Add(newCustomer{Id=1,FirstName="Joydip",LastName="Kanjilal",State="Telengana",City="Hyderabad",Address="Begumpet",Country="India"}); custList.Add(newCustomer{Id=2,FirstName="Steve",LastName="Jones",State="OA",City="NewYork",Address="LakeAvenue",Country="US"}); Predicate hydCustomers=x=>x.Id==1; Customercustomer=custList.Find(hydCustomers); Console.WriteLine(customer.FirstName); Console.Read(); }
当上面的代码被成功执行,控制台将会输出Joydip。
译文链接:https://www.infoworld.com/article/3057152/how-to-work-with-action-func-and-predicate-delegates-in-csharp.html?nsdr=true
总结
到此这篇关于C#中Action、Func和Predicate如何使用的文章就介绍到这了,更多相关C#中Action、Func和Predicate使用内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!