Java开发人员的C#:Lambdas

Lambda是一个匿名函数,可以分配给变量,可以作为方法的参数传递并可以随时调用。 我们可以在Java和C#中找到lambda,并且生成的代码非常相似。 Java lambda可以视为仅使用一种方法(称为a功能界面),而C#lambda可以分配给代表,这是Java中不存在的概念。 本文旨在解释lambda如何在Java和C#中工作,并强调它们之间的异同。

Java Functional Interfaces

在Java中,lambda可以简单地视为仅使用一种方法实现接口的匿名函数。 这种界面称为功能界面并可以用@FunctionalInterface告诉编译器强制执行唯一方法规则的注释:

@FunctionalInterface
interface Printer {
  void print(String message);
}
// The function interface is implemented with a lambda
Printer standardPrinter = message -> System.out.println(message);

// The print method of standardPrinter can be invoked
standardPrinter.print("Hello World!");

从前面的代码片段中,您应该注意,实现接口的方式绝对没有区别。 它可以是lambda,具体类甚至是匿名类。 无论如何,您只需调用打印接口的方法。

There are some pre-defined generic functional interfaces in the JDK that can be used directly off the shelf. The main ones are described below:

NameMethodRole
Function<T,R>R apply(T t)Takes an argument of a given type T and returns an object of type R
Consumer<T>void accept(T)Takes an argument of a given type T and does something useful (typically with side effects)
Predicate<T>boolean test(T)Takes an argument of a given type T and returns a boolean (similar to Function<T, Boolean>)
Supplier<T>T get()Returns an object of type T

C# Delegates

在C#中,可以将lambda分配给委托,委托是封装方法的类型:

delegate void Print(string message);
// A lambda is assigned to the delegate
Print print = message => System.Console.WriteLine(message);

// print can be directly invoked as a method
print("Hello World!");

像Java中一样,.NET框架中已经定义了一些委托,主要委托如下所述:

MethodRole
TResult Func<in T,out TResult>(T arg)Takes an argument of a given type T and returns an object of type TResult
void Action<in T>(T obj)Takes an argument of a given type T and does something useful (typically with side effects)
bool Predicate<in T>(T obj)Takes an argument of a given type T and returns a boolean (similar to Func<T, bool>)

Conclusion

从Java的角度来看,在API(例如Linq)中使用lambda很简单。 但是,在进行更深入的挖掘时,需要理解一些细微的差异。 我发现Java方法更简单,因为它没有引入其他概念,但是C#方法更干净,因为可以像方法一样直接调用委托。

from: https://dev.to//rnowif/c-for-the-java-developer-lambdas-1b6o

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值