[英]Mimic C# Actions in Java 8
动作很不错,因为您可以传递一个将void作为参数返回的任意函数。
用例? 任何函数包装,例如Timers。
所以基本上在C#中我可以编写一个方法
private static void Measure(Action block) {
var watch = new Stopwatch();
watch.Start();
block();
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
}
并像这样使用
public static void Main(string[] args) {
Measure(() => {Console.WriteLine("Hello");});
}
测量该方法所花费的时间。 漂亮整齐。 现在,如果我想用Java模仿它,我需要编写一个方法
private static <T> Consumer<T> measure(Consumer<T> block) {
return t -> {
long start = System.nanoTime();
block.accept(t);
System.out.printf("Time elapsed: %d Milliseconds\n", (System.nanoTime() - start) / 1000);
};
}
并像这样使用
public static void main(String[] args) {
measure(Void -> System.out.println("Hello")).accept(null);
}
问题 :
null
参数。 问题 :-我可以使用方法而不是外部使用者来模仿此方法,从而使null参数过时吗?
对于无参数方法,可以使用Runnable
代替Consumer
。
private static Runnable measure(Runnable block) {
return () -> {
long start = System.nanoTime();
block.run();
System.out.printf("Time elapsed: %d Milliseconds\n", (System.nanoTime() - start) / 1000);
};
}
接着:
public static void main(String[] args) {
measure(System.out::println("Hello")).run();
}
不过,现在我考虑了一下,您实际上不需要返回Runnable
:
private static void measure(Runnable block) {
long start = System.nanoTime();
block.run();
System.out.printf("Time elapsed: %d Milliseconds\n", (System.nanoTime() - start) / 1000);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.