C#中与Java 8的java.util.function.Consumer<>相当的是什么?

16

在C#中是否有这个接口的等价物?

例如:

Consumer<Byte> consumer = new Consumer<>();
consumer.accept(data[11]);

我搜索了一下 Func<>Action<>,但是我不知道它们是什么。

Consumer.accept() 接口的原始 Java 代码非常简单。但对于我来说并不简单:

void accept(T t);

/**
* Returns a composed {@code Consumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation.  If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code Consumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default Consumer<T> andThen(Consumer<? super T> after) {
    Objects.requireNonNull(after);
    return (T t) -> { accept(t); after.accept(t); };
}

2
这是Java代码,而我们是C#程序员,这个接口对我们来说并不简单:)这个消费者是做什么的? - blogprogramisty.net
2
任何只有一个参数且不返回值的委托类型都可以作为候选项。Action<T>就是其中之一。 - Dennis_E
1
你在寻找什么?这个问题本身就没有意义。有lambda表达式、回调函数、Observables、LINQ等,它们都可以完成你使用Consumer.accept的任何操作。 - Panagiotis Kanavos
我认为这会像以下的扩展方法一样:public static Action AndThen(this Action before, Action after) { return t => { before(t); after(t); }; }C# 使用扩展方法来替代默认方法。 - juharr
2
@PanagiotisKanavos action.Invoke(parameter)consumer.accept(parameter) 是同一件事情,只是它们被赋予了不同的名称。但我意识到这不是提问者的问题。 - Dennis_E
显示剩余7条评论
2个回答

19

"Consumer接口表示一个接受单个输入参数并且没有返回结果的操作。"

如果以上引用摘自这里是准确的,那么它大致等同于C#中的Action<T>委托;

例如,这段Java代码:

import java.util.function.Consumer;

public class Main {
  public static void main(String[] args) {
    Consumer<String> c = (x) -> System.out.println(x.toLowerCase());
    c.accept("Java2s.com");
  }
}

转换为C#代码如下:

using System;

public class Main
{
  static void Main(string[] args)
  {
     Action<string> c = (x) => Console.WriteLine(x.ToLower());
     c.Invoke("Java2s.com"); // or simply c("Java2s.com");
  }
}

3

Consumer<T> 对应于 Action<T>,而 andThen 方法是一个序列化运算符。你可以将 andThen 定义为扩展方法,例如:

public static Action<T> AndThen<T>(this Action<T> first, Action<T> next)
{
    return e => { first(e); next(e); };
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接